简体   繁体   English

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

[英]How to dynamically set arbitrary attributes for a class?

I'm trying to realize this just to see if it's possible: 我试图意识到这一点,只是看是否有可能:

And below is my current solution: 下面是我当前的解决方案:

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

But it's not complete, the fget and fdel function doesn't work well, for example 但这还不完整,例如,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

How to fix it? 如何解决?

Python already does that by itself: 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'

Read the documentation on the Python data model for more details. 阅读有关Python 数据模型的文档以了解更多详细信息。

Python indeeed already has this built into classes and objects by default. 默认情况下,Python确实已将其内置到类和对象中。

Your example fixed is: 您固定的示例是:

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: There isn't a lot to gain by these methods that simply wrap around the getattr , setattr and delattr builtins. 注意:这些方法仅封装了getattrsetattrdelattr内置delattr ,因此没有太多收获。

I'm the OP, and I found an example on python official doc which can do the things I want python properties 我是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.")

Let's examine it: 让我们检查一下:

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM