从类中的方法传递返回值的正确方法是什么?你总是在需要的时候调用该方法还是可以将返回的值存储在 init 方法中?假设我有:
class Foo():
def __init__(self):
def heavy_method(self):
#slow crunching
return crunch
def use_heavy_crunch(self):
data = self.heavy_crunch()
for i in data:
#do data stuff
#return data stuff
def other_func_that_need_heavy_method(self):
pass
d = Foo()
d.use_heavy_crunch()
我想知道的是上面的结构是正确的方式还是下面的方式是等效的或更好的?
class Foo()
def __init__(self):
self.data = None
def heavy_method(self):
#slow crunching
self.data = crunch
def use_heavy_crunch(self):
for i in self.data:
#do data stuff
#return data stuff
def other_func_that_need_heavy_method(self):
pass
d = Foo()
d.heavy_method()
d.use_heavy_crunch()
所以在上面的例子中,一个方法在另一个方法中被调用,而在下面的例子中,方法的返回值被传递给 init 方法中的一个变量,然后在另一个函数中使用。