Adding properties to objects
Matthew Barnes
matthew at barnes.net
Wed Apr 14 01:59:16 EDT 2004
Shalabh Chaturvedi <shalabh at cafepy.com> wrote...
> You can add properties dynamically, but to the type (i.e. 'class') and
> not the instance (i.e. 'object'). For your example:
>
> >>> x = Foo()
> >>> def f(a,b=None): # a bogus getter, setter, deleter
> ... print a,b
> ...
> >>> Foo.property = property(f,f,f)
> >>> x.property
> <__main__.Foo object at 0x008F3CB0> None
> >>> x.property = 1
> <__main__.Foo object at 0x008F3CB0> 1
> >>> del x.property
> <__main__.Foo object at 0x008F3CB0> None
> >>>
>
> This property will work for *all* instances of Foo.
Right. I may not have been clear, but I was trying to add different
properties to different *instances* of Foo.
> What is the problem you are trying to solve?
Here's basically what I was trying to do:
class Foo(object):
def __init__(self, sourcedict):
# sourcedict is a dictionary of objects having get() and set()
# methods. Nevermind where sourcedict comes from. The point
# is that different instances get different sourcedict's.
for name, object in sourcedict.items():
# This doesn't do what I had hoped for.
# My thinking was flawed on several levels.
self.__dict__['name'] = property(object.get, object.set)
So suppose "sourcedict" has some object named "bar". The idea was to
create properties on-the-fly based on the contents of "sourcedict",
such that:
>>> x = Foo(sourcedict) # Given this...
>>> x.bar # would invoke sourcedict['bar'].get()
>>> x.bar = 1 # would invoke sourcedict['bar'].set(1)
I've since realized that properties are not the right approach for
something like this, and that I would be better off with a more
straight-forward approach using custom Foo.__getattr__ and
Foo.__setattr__ methods (seems obvious now that I've simplified the
problem description :-).
Matthew Barnes
More information about the Python-list
mailing list