2017-10-21 89 views
-1

我建立了一个类来处理很多不同的函数,它们采用通用输入。但是,我刚碰到需要更改通过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 

谢谢!

+2

究竟什么是您遇到的问题?据我所知,您发布的代码完全符合您的期望。 –

+0

请注意,如果你想'self.test_var',你可以调用'self.some_function'。 –

+0

除了不能多次调用'some_function'之外,'test_variable'最初是否定的,这是什么问题? – James

回答

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 
+2

您已经从该方法中删除了“@属性”装饰器。我认为这可能是他/她有问题的地方。 – James