每当object.x更新时,请制作一些重新计算object._x的代码。我打算将object._x作为object和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()
也应该发生。
答案 0 :(得分:2)
听起来我希望x
成为property
。属性是您存储在调用" 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
答案 1 :(得分:0)
你也可以像这样使用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)
您可以通过创建类的实例来查看属性:
>>> obj = MyClass('123')
>>> obj.x
Accessing private attribute x: 123
'123'
>>> obj.x = 456
Changing private attribute x to 456