How to put my function in to class.Beginner

后端 未结 1 945
抹茶落季
抹茶落季 2021-01-24 10:37

I have a Json function below need to construct a class having two function, How my second function will \"know\" that the data which is response from first function

相关标签:
1条回答
  • 2021-01-24 11:04

    You have to save your data as a property of the underlying self object of your class, e.g.:

    class MyJson():
        def func1(self):
            self.data = ...
        def func2(self):
            return Response(self.data, ...)
    
    
    x = MyJson()
    x.func1()
    y = x.func2()
    

    Note that it is a good programming practice not to introduce new class attributes outside the constructor, so in practice you may want to add to the __init__() method something to initialize self.data, e.g.:

    class MyJson():
        def __init__(self):
            self.data = None
        def func1(self):
            self.data = ...
        def func2(self):
            return Response(self.data, ...)
    

    EDIT

    (To address the request for a more reputable source.)

    Essentially, all the elements can be found in the official Python tutorial on the chapter dedicated to classes.

    Of particular relevance to this question are:

    • the discussion on scopes
    • the introduction of the class objects
    • the discussion on class and instance variables
    • some parts of the random remarks (especially at the end)
    0 讨论(0)
提交回复
热议问题