How to assign a property to an instance in Python?

Using python, you can set the instance attribute using one of the following two methods:

>>> class Foo(object):
    pass

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

You can also assign properties through 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 strange property object. Similar experiments yielded similar results. I assume that properties are more closely related to classes than instances in some respects, but I don’t know that the inner workings are good enough to understand what is going on here.

+5
source share
4

:

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

. :

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

. ? .

+4

descriptors, , , . , .

>>> class Foo(object):
...     @property
...     def x(self):
...         if 'x' in self.__dict__:
...             return self.__dict__['x'](self)
... 
>>> a = Foo()
>>> def k(self):
...     return 0
... 
>>> a.__dict__['x'] = k
>>> a.x
0
+2

:

>>> class Foo(object):
    pass    
>>> a = Foo()
>>> a.__class__
__main__.Foo    
>>> setattr(a.__class__, 'm', property(lambda self: 0))
>>> a.m
0 
>>> a.m = 24
AttributeError: can't set attribute
+1

@agf lambda .

class A(object):
    pass

a = A()
a.__class__.f = property(lambda self: 57)
a.f  # 57

The following post provides more context: https://crosscompute.com/n/jAbsB6OIm6oCCJX9PBIbY5FECFKCClyV/_/Assign%20a%20class%20property%20to%20an%20instance

0
source

All Articles