ZengJuchen
ZengJuchen

Reputation: 4811

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?

Upvotes: 1

Views: 1109

Answers (3)

ZengJuchen
ZengJuchen

Reputation: 4811

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'

Upvotes: 0

James Mills
James Mills

Reputation: 19030

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.

Upvotes: 2

jbaiter
jbaiter

Reputation: 7099

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.

Upvotes: 7

Related Questions