2.2 properties and subclasses

Tim Peters tim.one at comcast.net
Mon May 19 20:49:30 EDT 2003


[Tim]
> 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.

[Miles Egan]
> This is the behavior I was expecting.  I guess what I really want here
> is a simple way to implement properties in the base class and
> intercept access to them in some cases in subclasses (lazy
> initialization, etc).
>
> Why don't you recommend this?  It seems like a pretty natural solution
> to my current problem.

Just because it's clearer, and more efficient at runtime, to repeat

    prop = property(get_prop)

in both classes.  For that matter, it would be clearer and more efficient
still to have clients call get_prop() directly and skip the property layer,
but I appreciate that may be less convenient for clients.  The two ways of
implementing with properties look the same to clients.






More information about the Python-list mailing list