请编写一些代码,以便在更新 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/