Fun with python properties
I ran into an oddity of something I wanted to do with python properties while playing with my music server the yesterday. After a little futzing, I found a way around my problem. Read on to find out how to do python properties and inheritance.
Assume we have two classes. The first,
Base, provides property-style access to some attributes. Straightforward get and set. The
Derived class wants the same thing, but wants to change the default “unset” value for property
In the absence of property (dot-style) access, it would just be a matter of overriding
getFoo(). To make property access work right, we must get a little bit clever.
At first it seems simple. Just point the arguments to
property() to the get and set functions and be done with this. Seems obvious:
class Base(object): def __init__(self): self.foo = None def getFoo(self): return self.__foo def setFoo(self, val): self.__foo = val # Seemingly obvious solution: # foo = property(fget=getFoo, fset=setFoo) # # Actual solution: foo = property(fget=lambda self: self.getFoo(), fset=lambda self, v: self.setFoo(v) ) class Derived(Base): def getFoo(self): """Same as in Base, but default to 0 instead of None.""" result = super(Derived, self).getFoo() if result != None: return result else: return 0 if __name__ == "__main__": t1 = Base() print t1.foo t1.foo = "Something" print t1.foo print t2 = Derived() print t2.foo t2.foo = "bar" print t2.foo
I was pretty impressed with myself for figuring this out. So I’m putting it on my site to pat myself on the back. Turns out, after my initial bitching, that python is actually pretty cool.