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

标签 python class private

请编写一些代码,以便在更新 object.x 时重新计算 object._x。我希望 object._x 成为 object 的“私有(private)”属性,而 object.x 成为“虚拟变量”,其唯一目的是设置 object._x 的值。

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 成为一个属性。属性是存储在类中的对象,当它作为类实例的属性被访问或分配时,该对象会调用“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

关于python - 每当修改其他实例属性时,自动更新某些 "private"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29293773/

相关文章:

python - 如何从python列表中过滤一些url?

android - 用另一个类更改一个类的 TextView

php - 关于使用类的类的开始 OOP 问题

angularjs - 在 angular2 constructor() 中使用 private 与 public 关键字有什么不同

Python 正则表达式查找单词中间具有指定字符且不以字符开头或结尾的单词。

python - 我可以可靠地使用 python 字典键方法生成的列表索引吗?

python - 从查询中生成 Memcache 键

c++ - 模仿结构/类之间的 C#/D 差异是否是好的 C++ 风格?

swift - 为什么访问控制有用?

c# - 拥有带有私有(private)访问器的公共(public)领域是否有意义?