2.2 properties and subclasses
Tim Peters
tim.one at comcast.net
Mon May 19 17:43:08 EDT 2003
[Miles Egan]
> This prints "BASE" instead of "SUB". Is this right?
Yes.
> class BaseClass(object):
> def __init__(self):
> self._prop = "BASE"
>
> def get_prop(self): return self._prop
> prop = property(get_prop)
>
> class SubClass(BaseClass):
> def get_prop(self): return "SUB"
This overrides BaseClass.get_prop, but the class ends here and nothing gave
the name "prop" a new meaning in SubClass.
> b = BaseClass()
> print b.prop
Executes BaseClass.prop.
> s = SubClass()
> print s.prop
Also executes BaseClass.prop.
Add
prop = property(get_prop)
to the end of SubClass to get what I think you're trying to get. Note that
the
prop = property(get_prop)
lines are executed at class-definition time. Whatever value for get_prop is
current *when* the class is being defined is the value of get_prop used.
This isn't a "thunk" that looks up the value of get_prop at the time calls
are executed.
If you think that's what you want (I don't recommend it), you could, e.g.,
write the stuff this way instead:
class BaseClass(object):
def __init__(self):
self._prop = "BASE"
def get_prop(self): return self._prop
prop = property(lambda self: self.get_prop()) # the only change
class SubClass(BaseClass):
def get_prop(self): return "SUB"
Then the (still shared) prop dynamically looks up which get_prop() to use on
each invocation, and only get_prop needs to be overridden in SubClass.
More information about the Python-list
mailing list