如何动态设置类的任意属性?

时间:2014-07-18 08:15:36

标签: python

我试图意识到这是否可能:

以下是我目前的解决方案:

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 :(得分: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 data model的文档以获取更多详细信息。

答案 1 :(得分:2)

默认情况下,Python indeeed已将其内置到类和对象中。

您修复的示例是:

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)

NB:这些方法无法轻易绕过getattrsetattrdelattr内置网站。

答案 2 :(得分:0)

我是OP,我在python官方文档上找到了一个例子,可以做我想要的事情python properties

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'