我希望变量不仅仅是在我设置它时设置。 和界面尽可能干净。
简短:我想要的是什么:
# 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
但是后来我有2个不同的东西可供使用.. 好的,我可以创建一个与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
并且也有一些事情开始变得更好。
答案 0 :(得分:3)
我认为你想要python属性。检查this out。类似的东西:
class Test:
def __init__(self):
self._var = 1
@property
def var(self):
return self._var
@var.setter
def var(self, value):
# add stuff here that you want to happen on var assignment
self._var = value
答案 1 :(得分:1)
您可以使用property。请注意,如果setter方法很昂贵,最好使用方法。人们期望属性访问速度很快。
class Foo(object):
def __init__(self):
self._var = None
@property
def var(self):
return self._var
@var.setter
def var(self, whatever):
self._var = whatever
do_whatever()
x = Foo()
print x.var # prints None
x.var = 2 # sets x.var and does whatever