Inheriting property functions

Aahz aahz at
Sat Oct 21 04:54:33 CEST 2006

In article <1161383286.543397.46700 at>,
Dustan <DustanGroups at> wrote:
>>>> class A(object):
>	def __init__(self, a):
>		self.a = a
>	def get_a(self): return self.__a
>	def set_a(self, new_a): self.__a = new_a
>	a = property(get_a, set_a)
>>>> class B(A):
>	b = property(get_a, set_a)

BTW, since you're almost certainly going to run into this quickly given
the direction your code is taking (and also to fix some bugs):

class A(object):
    def __init__(self, a):
        self._a = a

    def get_a(self):
        return self._a

    def _get_a(self):
        return self.get_a()

    def set_a(self, new_a):
        self._a = new_a

    def _set_a(self, new_a):

    a = property(_get_a, _set_a)

class B(A):
    def get_a(self):
        return str(self._a)

Thank Alex Martelli for this demonstration that programming is all built
on one basic trick: add another layer of indirection.  However, I leave
you to figure out on your own why this is better.

Note carefully that I changed __a to _a.  You almost never want to use
double-underscore private names because of the way they cause problems
with inheritance.

PS: Please do NOT post code with TABs
Aahz (aahz at           <*>

"If you don't know what your program is supposed to do, you'd better not
start writing it."  --Dijkstra

More information about the Python-list mailing list