[英]How to dynamically set arbitrary attributes for a class?
我试图意识到这一点,只是看是否有可能:
下面是我当前的解决方案:
class A(object):
def fset(self, x, value):
self.__dict__.update({x:value})
def fget(self, x):
return self.x
def fdel(self, x):
del self.x
但这还不完整,例如,fget和fdel函数无法正常工作
>>> a = A()
>>> a.fset('z', 5)
>>> a.z
5
>>> a.fget('z')
'A' object has no attribute 'x'
>>> a.fget(z)
name 'z' is not defined
>>> a.fdel(z)
NameError: name 'z' is not defined
>>> a.fdel('z')
AttributeError: x
如何解决?
Python已经自己做到了:
>>> class A(object):
pass
>>> a = A()
>>> setattr(a, 'z', 5)
>>> a.z
5
>>> getattr(a, 'z')
5
>>> delattr(a, 'z')
>>> a.z
AttributeError: 'A' object has no attribute 'z'
阅读有关Python 数据模型的文档以了解更多详细信息。
我是OP,我在python官方文档上找到了一个示例,该示例可以执行我想要的python属性
class C(object):
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
让我们检查一下:
>>> c = C()
>>> c.yyy = 123
>>> c.yyy
123
>>> del c.yyy
>>> c.yyy
AttributeError: 'C' object has no attribute 'yyy'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.