如何动态设置类的任意属性?
我正在尝试实现这个功能,只是想看看是否可行:
下面是我目前的解决方案:
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
该怎么修复呢?
3 个回答
0
我是这个问题的提问者,我在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'
2
其实,Python已经默认在类和对象中内置了这些功能。
你的例子修正后是:
class A(object):
def fset(self, x, value):
setattr(self, x, value)
def fget(self, x):
return getattr(self, x)
def fdel(self, x):
delattr(self, x)
注意:这些方法其实只是简单地包装了内置的 getattr
、setattr
和 delattr
,所以用处不大。
7
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的数据模型文档。