Add Properties to Instances?
bokr at oz.net
Sun Mar 13 04:18:51 CET 2005
On 12 Mar 2005 09:48:42 -0800, "Martin Miller" <ggrp1.20.martineau at dfgh.net> wrote:
>I'm trying to create some read-only instance specific properties, but
>the following attempt didn't work:
>> class Foobar(object):
>> foobar = Foobar()
>> foobar.x = property(fget=lambda: 42)
>> print "foobar.x:", foobar.x
>Which results in the following ouput instead of '42':
> foobar.x: <property object at 0x00AE57B0>
>I also tried this:
>> foobar.__dict__['x'] = property(fget=lambda: 42)
>but get the same behavior.
>Can anyone tell me what's wrong with this approach (and perhaps the
>correct way to do it, if there is one)?
One way is to doctor the instance attribute access to do what
happens with a property when it is implemented normally as an
attribute of the class. E.g., (using InstProp in place of your Foobar)
>>> class InstProp(object):
... def __getattribute__(self, attr):
... p = object.__getattribute__(self, attr)
... if isinstance(p, property): return p.__get__(self)
... return p
>>> import time
>>> inst1 = InstProp()
>>> inst2 = InstProp()
>>> inst1.t = property(lambda self: time.ctime())
>>> inst2.p2 = property(lambda self: 'prop2')
'Sat Mar 12 19:10:40 2005'
If you want robust writeable and/or deleteable properties, you will have
to do a little more work, but it can be done.
More information about the Python-list