[Tutor] Inheritance in classes

Steven D'Aprano steve at pearwood.info
Tue Apr 8 16:49:29 CEST 2014


On Tue, Apr 08, 2014 at 11:14:36AM +0530, Santosh Kumar wrote:
> Can i mask the parent attibutes in the child. let me give a quick example.
> 
> In [1]: class a:
>    ...:     value1 = 1
>    ...:     value2 = 2
>    ...:
> 
> In [2]: class b(a):
>    ...:     value3 = 3
>    ...:

All of value1, value2, value3 here are *class attributes*, bound to the 
class, not the instance. In Java terms, that is similar to static 
variables.

For the purpose of your example, that is not very important, but it can 
make a difference.


> In [3]: obj1 = b()
> 
> In [4]: obj1.value1
> Out[4]: 1
> 
> In [5]: obj1.value2
> Out[5]: 2
> 
> In [6]: obj1.value3
> Out[6]: 3
> 
> If you notice in the below example you will see that the child class object
> ``obj1`` has inherited all the attibutes of the parent class.


That is how object oriented programming is supposed to work. If you 
don't want to inherit the attributes of class "a", you should not 
inherit from class "a".


> Is there a
> way by which i can make the child class not inherit some of the properites
> of parent class.

There is, but *you should not do this*. This is poor design, and 
violates the Liskov Substitution Principle:

https://en.wikipedia.org/wiki/Liskov_substitution_principle
http://www.oodesign.com/liskov-s-substitution-principle.html

But what we can do is inherit from a, but over-ride access to one of the 
attributes and fake an attribute error. But really, you should not do 
this -- it is poor design.

py> class A:
...     value1 = 23
...     value2 = 42
...
py> class B(A):
...     value3 = 17
...     @property
...     def value1(self):
...             raise AttributeError("Fake!")
...
py> obj = B()
py> obj.value1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in value1
AttributeError: Fake!
py> obj.value2
42
py> obj.value3
17


-- 
Steven


More information about the Tutor mailing list