Adding properties to an instance

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Wed Feb 6 17:09:59 EST 2008


On 6 fév, 21:06, dg.google.gro... at thesamovar.net wrote:
> Hi all,
>
> So I understand that properties belong to a class not an instance, but
> nonetheless I want to add properties to an instance.

While this is technically possible (I tried a couple years ago), it
requires hacking the __getattribute__ method, which is something I
would not recommand, not only because it can be tricky, but mostly
because this is a very critical path wrt/ perfs.  (IIRC it also
required using custom descriptors, but I'm not really sure about this
last point).

> I have a class
> which when an instance is created runs some fairly complicated code
> and produces a set of names which I'd like to be able to access via
> properties. At the moment, I'm using something like obj.getvar(name)
> but I'd like to be able to write obj.name.

Before new-style classes, we used the __getattr__/__setattr__ hooks
for computed attributes. While this approach is now a bit abandonned
in favor of descriptors (properties or custom ones), it still works
fine, and is probably the best solution to your problem.

HTH




More information about the Python-list mailing list