Why property works only for objects?

Steven Bethard steven.bethard at gmail.com
Fri Mar 10 04:53:27 CET 2006

Michal Kwiatkowski wrote:
> Code below shows that property() works only if you use it within a class.

Yes, descriptors are only applied at the class level (that is, only 
class objects call the __get__ methods).

> Is there any method of making descriptors on per-object basis?

I'm still not convinced that you actually want to, but you can write 
your own descriptor to dispatch to the instance object (instead of the 

 >>> class InstanceProperty(object):
...     def __init__(self, func_name):
...         self.func_name = func_name
...     def __get__(self, obj, type=None):
...         if obj is None:
...             return self
...         return getattr(obj, self.func_name)(obj)
 >>> class C(object):
...     x = InstanceProperty('_x')
 >>> c = C()
 >>> c.x
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "<interactive input>", line 7, in __get__
AttributeError: 'C' object has no attribute '_x'
 >>> def getx(self):
...     return 42
 >>> c._x = getx
 >>> c.x


More information about the Python-list mailing list