我想要一个变量做的不仅仅是在我设置它时设置它。并且界面尽可能干净。
简短:我想要什么:
# have class with a variable that I can access:
print myInstance.var
42
# change the variable
myInstance.var = 23
# have the change kick off another method:
self.var was changed: 23!!
嗯..所以我能做什么:使用变量和setter方法:
class Test:
def __init__(self):
self.var = 1
print( 'self.var is: ' + str(self.var) )
def setVar(self, value):
self.var = value
print( 'self.var changed: ' + str(self.var) )
t = Test()
self.var is: 1
# so I have t.var at hand:
print t.var
1
# and change it this way
t.setVar(5)
self.var changed: 5
但是后来我有两个不同的东西可以使用.. 好的,我可以制作一个与 var 交互的方法:
class Test:
def __init__(self):
self.var = 1
print( 'self.var is: ' + str(self.var) )
def method(self, value=None):
if value == None:
return self.var
self.var = value
print( 'self.var changed: ' + str(self.var) )
t = Test()
self.var is: 1
# to get the value then:
print t.method()
1
# to set it:
t.method(4)
self.var changed: 4
# and verifiy:
print t.method()
4
这已经很好了。我在其他语言的不同帖子中看到过它。但我不知道。python中有更好的解决方案吗?!?
也许我是偏执狂,但对我来说,做t.var = 5
一些事情也会让我感觉更好。