我试图通过init变量传递一些参数(进入类Dog中继承的类Cat)。
我想要做的是:只要Cat中的方法使用self.dynamic变量,他们就会调用该函数。相反,使用此代码,它只是从第一个函数调用发送结果。
(错误的例子)
class Dog(object):
def __init__(self):
self.var = None
self.dynamic = self.function()
def change_var(self):
self.var = 'something'
print 'var has something'
def function(self):
if self.var:
return 'full'
else:
return 'empty'
def final_function(self):
return 'it is ' + self.dynamic
my_instance = Dog()
print my_instance.dynamic
>>>empty # as it should
my_instance.change_var()
>>>var has something # as it should
print my_instance.final_function()
>>>it is empty # it didnt update since 'self.var' has the first value stored
我通过使用lambda找到了解决方案,但我不确定这是最好的方法。
class Dog(object):
def __init__(self):
self.var = None
self.dynamic = lambda: self.function()
def change_var(self):
self.var = 'something'
print 'var has something'
def function(self):
if self.var:
return 'full'
else:
return 'empty'
def final_function(self):
return 'it is ' + self.dynamic()
my_instance = Dog()
print my_instance.dynamic()
>>>empty # as it should
my_instance.change_var()
>>>var has something
print my_instance.final_function()
>>>it is full # it works!!
有没有更好的方法来做到这一点?
PS:不确定我是否使用正确的词来描述事物,但我是编程(和Python)的新手。
答案 0 :(得分:2)
你不需要lambda。函数和方法已经是第一类对象,可以分配给变量:
self.dynamic = self.function
虽然我必须说我不知道其中任何一个是直接调用self.function给你的。