我构建了一个类来处理许多带有常见输入的不同函数。但是,我刚遇到需要更改通过self
传递的变量之一的情况。我该怎么做呢?这是一个例子:
class Test:
def __init__(self, test_variable):
self.test_var = test_variable
@property
def some_function(self):
if self.test_var < 0:
self.test_var = 'New Output' #this is the line that I can't get
#get to work and I was hoping to update it here
#so I could use it in later functions
return self.test_var
谢谢!
答案 0 :(得分:1)
您应该删除@property
属性。然后,您可以通过执行x.test_var = 5
来设置它。如,
class Test:
def __init__(self, test_variable):
self.test_var = test_variable
def some_function(self):
if self.test_var < 0:
self.test_var = 'New Output' #this is the line that I can't get
#get to work and I was hoping to update it here
#so I could use it in later functions
return self.test_var
x = Test(-1)
print(x.some_function())
x.test_var = 5
print(x.some_function())
返回
New Output
5