[Tutor] Inheritance in classes
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 : class a:
> ...: value1 = 1
> ...: value2 = 2
> In : 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
For the purpose of your example, that is not very important, but it can
make a difference.
> In : obj1 = b()
> In : obj1.value1
> Out: 1
> In : obj1.value2
> Out: 2
> In : obj1.value3
> Out: 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:
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
... def value1(self):
... raise AttributeError("Fake!")
py> obj = B()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in value1
More information about the Tutor