Why property works only for objects?

Michal Kwiatkowski ruby at no.spam
Fri Mar 10 05:45:18 CET 2006

Steven Bethard napisał(a):
>> 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
> type):

Ok, this works for attributes I know a name of at class definition. What
about other situations? I could possibly want to have different sets of
attributes for instances of a class. Is it still possible to do? I don't
also like current solution, as it wraps things around, creating another
attribute ('_x') in the process. Aren't there any cleaner solutions?

The problem is I have an instance of a given class (say BaseClass) and I
want it to implement some attribute accesses as method calls. I'm not a
creator of this object, so changing definition of BaseClass or
subclassing it is not an option. Code below doesn't work, but shows my

# obj is instance of BaseClass
def get_x(self):
    # ...
def set_x(self, value):
    # ...
obj.x = property(get_x, set_x)

Changing __setattr__/__getattr__ of an object also doesn't work for the
same reason: dictionary lookup is made only in class attributes,
ommiting object attributes. It's confusing, because writting obj.x and
obj.__getattribute__('x') gives a different results. There also seems
not to be any clear way to define methods for objects. Something like:

class C(object):

def method(self):
    return self.x

c = c.x
c.method = method
c.method() # => AttributeError

So another question arise. Is it possible to make function a method (so
it will receive calling object as first argument)?

 . o .       >>  http://joker.linuxstuff.pl  <<
 . . o   It's easier to get forgiveness for being wrong
 o o o   than forgiveness for being right.

More information about the Python-list mailing list