[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] offtopic - inheritance and property()



On, Wed Jan 11, 2006, altern wrote:

[...] 
> So i am trying to find solutions to this but so far the only way it is 
> too completely overwrite the setter and getter and create again the 
> property() in the subclass. So i have to repeat all the code from the 
> superclass ... I also tried some hacks. They kind of work but they feel 
> to me like too weird to be a good solution.
> 
> Could anyone suggest some nicer way to be able to extend those inherited 
> methods while still using the property() system?

I had the same issue and besides the usage of meta classes, overriding
the set_X() methods in the subclasses, rebinding the property in the
subclass, etc. I discovered an easy way of accomplishing what you want
by using lambda:

class Foo:
   def set_X (self, x):
       ...
   def get_X (self):
       ...
   x = property (lambda self: self.get_X (),
                 lambda self, var: self.set_X (var), ...)

The second var argument in the setter is important here to receive the
wanted assignment value, os do not forget it ;-).

This also works fine in a similar way with multiple arguments:

    x = property (lambda self: self.get_X (),
                  lambda self, (var1, var2): self.set_X (var1, var2), ...)

The property then would allow something like that:

foo_instance.x = "foo", "bar"

You can safely override the set_X(), get_X() methods in a subclass without
worrying about the property anymore (as it is resolved at runtime).
Because of this a small runtime overhead might occur, but I could not
measure it for now.

Regards
Marcus

Attachment: pgpQP65EzpPMs.pgp
Description: PGP signature