简体   繁体   中英

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

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

>>> 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 indeeed already has this built into classes and objects by default.

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.

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

Let's examine it:

>>> c = C()
>>> c.yyy = 123
>>> c.yyy
123
>>> del c.yyy
>>> c.yyy
AttributeError: 'C' object has no attribute 'yyy'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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