0

我想要一个变量做的不仅仅是在我设置它时设置它。并且界面尽可能干净。

简短:我想要什么:

# 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一些事情也会让我感觉更好。

4

2 回答 2

3

我想你想要 python 属性。看看这个。就像是:

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
于 2013-07-18T15:08:54.473 回答
1

你可以使用一个属性。请注意,如果 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
于 2013-07-18T15:05:38.417 回答