Add Properties to Instances?
Steven Bethard
steven.bethard at gmail.com
Sat Mar 12 13:08:40 EST 2005
Martin Miller wrote:
> I'm trying to create some read-only instance specific properties, but
> the following attempt didn't work:
>
>
>>class Foobar(object):
>> pass
>>
>>foobar = Foobar()
>>foobar.x = property(fget=lambda: 42)
>>
>>print "foobar.x:", foobar.x
>
[snip]
>
> Can anyone tell me what's wrong with this approach (and perhaps the
> correct way to do it, if there is one)?
Properties cannot be defined on a per-instance basis. Properties must
be defined at the class level. So you need to do something like:
py> class Foobar(object):
... x = property(fget=lambda self: 42)
...
py> Foobar().x
42
or
py> class Foobar(object):
... pass
...
py> Foobar.x = property(fget=lambda self: 42)
py> Foobar().x
42
If you want to have different properties on different instances, you'll
need to make each of the different instances a different subtype of
Foobar, e.g.:
py> class Foobar(object):
... pass
...
py> foobar = type('FoobarSub', (Foobar,),
... dict(x=property(fget=lambda self: 42)))()
py> foobar.x
42
py> Foobar().x
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: 'Foobar' object has no attribute 'x'
What's the situation in which you think you want different properties
for different instances of the same class?
STeVe
More information about the Python-list
mailing list