Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assign a property to an instance in Python?

Using python, one can set an attribute of a instance via either of the two methods below:

>>> class Foo(object):
    pass

>>> a = Foo()
>>> a.x = 1
>>> a.x
1
>>> setattr(a, 'b', 2)
>>> a.b
2

One can also assign properties via the property decorator.

>>> class Bar(object):
    @property
    def x(self):
        return 0


>>> a = Bar()
>>> a.x
0

My question is, how can I assign a property to an instance?

My intuition was to try something like this...

>>> class Doo(object):
    pass

>>> a = Doo()
>>> def k():
    return 0

>>> a.m = property(k)
>>> a.m
<property object at 0x0380F540>

... but, I get this weird property object. Similar experimentation yielded similar results. My guess is that properties are more closely related to classes than instances in some respect, but I don't know the inner workings well enough to understand what's going on here.

like image 829
Ceasar Bautista Avatar asked Aug 19 '11 06:08

Ceasar Bautista


1 Answers

It is possible to dynamically add properties to a class after it's already created:

class Bar(object):
    def x(self):
        return 0

setattr(Bar, 'x', property(Bar.x))

print Bar.x
# <property object at 0x04D37270>
print Bar().x
# 0

However, you can't set a property on an instance, only on a class. You can use an instance to do it:

class Bar(object):
    def x(self):
        return 0

bar = Bar()

setattr(bar.__class__, 'x', property(bar.__class__.x))

print Bar.x
# <property object at 0x04D306F0>
print bar.x
# 0

See How to add property to a class dynamically? for more information.

like image 183
agf Avatar answered Sep 18 '22 17:09

agf