Inheriting property functions

mdsteele at gmail.com mdsteele at gmail.com
Fri Oct 20 18:52:16 EDT 2006


Dustan wrote:
> B isn't recognizing its inheritence of A's methods get_a and set_a
> during creation.
>
> Why am I doing this? For an object of type B, it makes more sense to
> reference the attribute 'b' than it does to reference the attribute
> 'a', even though they are the same, in terms of readability.
>
> Is there any way to make this work as intended?

Try this:

>>> 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(A.get_a,A.set_a)
...
>>> bar = B(5)
>>> bar.a
5
>>> bar.b
5

The trouble is that get_a and set_a are attributes of the _class
object_ A.  Instances of A (and hence, instances of B) will see them,
but the class B will not, so you have to point to them explicitly with
A.get_a and A.set_a.




More information about the Python-list mailing list