一个关于getattr的有关问题
请教大家一个关于getattr的问题
大家好,想请教一个通过getattr方法获取对象的property的问题,下面是代码,为什么我通过getattr获得的x只能读,无法设置呢?有什么办法可以设置吗?谢谢
class test:
def __init__(self,x):
self._x = x
def setx(self,x):
self._x = x
def getx(self):
return self._x
x = property(getx,setx)
t = test(1)
x = getattr(t,'x')
print x #这里输出时1
x = 2
print x #这里输出是2
print t.x #这里输出是1
------解决方案--------------------
property([fget[, fset[, fdel[, doc]]]])
Return a property attribute for new-style classes (classes that derive from object).
class test(object):酱紫比较好,t.x=2的时候 self._x=2,相当合理,然而
旧式类却掠过property会新生self.x=2,self._x还是1,旧的还是用回__getattr__,__setattr__把关会正常些
------解决方案--------------------
代碼和結果沒錯啊。
如果你要設置屬性要用
t.x=2
而不是
x=2
當你對一個變量名稱重新賦值時,就成為兩個不同的對象了。
------解决方案--------------------
Everything in Python is an object
大家好,想请教一个通过getattr方法获取对象的property的问题,下面是代码,为什么我通过getattr获得的x只能读,无法设置呢?有什么办法可以设置吗?谢谢
class test:
def __init__(self,x):
self._x = x
def setx(self,x):
self._x = x
def getx(self):
return self._x
x = property(getx,setx)
t = test(1)
x = getattr(t,'x')
print x #这里输出时1
x = 2
print x #这里输出是2
print t.x #这里输出是1
------解决方案--------------------
property([fget[, fset[, fdel[, doc]]]])
Return a property attribute for new-style classes (classes that derive from object).
class test(object):酱紫比较好,t.x=2的时候 self._x=2,相当合理,然而
旧式类却掠过property会新生self.x=2,self._x还是1,旧的还是用回__getattr__,__setattr__把关会正常些
------解决方案--------------------
代碼和結果沒錯啊。
如果你要設置屬性要用
t.x=2
而不是
x=2
當你對一個變量名稱重新賦值時,就成為兩個不同的對象了。
------解决方案--------------------
Everything in Python is an object