每当修改某些其他实例属性时自动更新某些 "private" 属性

Automatically update some "private" attribute whenever some other instance attribute is modified

请编写一些代码,以便在 object.x 更新时重新计算 object._x。我打算 object._x 成为对象的 "private" 属性,而 object.x 成为 "dummy variable" 其唯一目的是设置 object._x.[=14 的值=]

class tihst(object):
    def __init__(self,object):
        self.x=object
        self.xRecall()
    def xPrivate(self):
        if type(self.x)==float:
            self._x=self.x
        elif type(self.x)==int:
            self._x=float(self.x)
        elif type(self.x)==str:
            self._x=self.x
        else:
            self._x="errorStatus001"
    def xRecall(self):
        print "private x is :"
        self.xPrivate()
        print self._x

aone=tihst("002")
print vars(aone)

例如:如果用户做出诸如 object.x="5.3" 的声明,那么指令 object.xPrivate() 也应该出现。

我觉得你希望 x 成为 property。 属性 是存储在 class 中的对象,当它作为 [=19] 实例的属性被访问或分配时调用 "getter" 和 "setter" 函数=].

试试这个:

class MyClass(object):
    def __init__(self, val):
        self.x = val   # note, this will access the property too

    @property          # use property as a decorator of the getter method
    def x(self):
        return self._x

    @x.setter          # use the "setter" attribute of the property as a decorator
    def x(self, value):
        if isinstance(value, (float, int, str)):  # accept only these types
            self._x = val
        else:
            self._x = "Error" # it might be more "Pythonic" to raise an exception here

您也可以这样使用property

class MyClass(object):

    def __init__(self, x):
        self._x = x

    def access_x(self):
        print 'Accessing private attribute x:', self._x
        return self._x

    def change_x(self, new_x):
        print 'Changing private attribute x to', new_x
        # You can add some extra logic here ...
        self._x = new_x

    x = property(access_x, change_x)

您可以通过创建 class:

的实例来查看 属性 的实际效果
>>> obj = MyClass('123')

>>> obj.x
Accessing private attribute x: 123
'123'

>>> obj.x = 456
Changing private attribute x to 456