如何将我的函数放入课堂. [英] How to put my function in to class.Beginner
问题描述
我有一个Json函数,下面需要构造一个具有两个函数的类,我的第二个函数将如何知道" data
是第一个函数的响应
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
def results():
json_request = request.get_json()
data = json.loads(json.dumps(json_request))
return Response(data, mimetype='xml/html')
我的伪代码如下:
class Myjson():
def function_one():
json_request = request.get_json()
data = json.loads(json.dumps(json_request))
def function_two():
return Response(data, mimetype='xml/html')
推荐答案
您必须将data
保存为类的基础self
对象的属性,例如:
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()
请注意,最好不要在构造函数之外引入新的类属性,因此在实践中,您可能需要向__init__()
方法中添加一些初始化self.data
的内容,例如:
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.)
基本上,所有元素都可以在官方Python教程中找到专门用于类的章节.
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)
这篇关于如何将我的函数放入课堂.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!