[英]Best way to make variables in init refer to a function's return
I m trying to pass some arguments through the init variables (into class Cat that is inherited in class Dog). 我试图通过init变量传递一些参数(进入在Dog类中继承的Cat类)。
What i want to do is: whenever methods in Cat use the self.dynamic variable they call the function. 我想做的是:每当Cat中的方法使用self.dynamic变量时,它们都会调用该函数。 Instead, with this code, it just sends the result from the first function call. 而是使用此代码,它只是从第一个函数调用中发送结果。
(wrong example) (错误的例子)
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
I found a solution by using lambda, but im not sure this is the best way to do it. 我通过使用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!!
Is there a better way to do the above? 有没有更好的方法来执行以上操作?
PS: Not sure if i use the correct words to describe things, but im new to programming (and Python). PS:不确定我是否使用正确的词来描述事物,但不是编程(和Python)的新手。
You don't need the lambda. 您不需要lambda。 Functions and methods are already first class objects, and can be assigned to variables: 函数和方法已经是一流的对象,并且可以分配给变量:
self.dynamic = self.function
Although I must say I don't know what either of these are giving you over just calling self.function directly. 尽管我必须说,我不知道直接调用self.function会给您带来什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.