Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and init method in Python

I'm begginer of python. I can't understand inheritance and __init__().

class Num:     def __init__(self,num):         self.n1 = num  class Num2(Num):     def show(self):         print self.n1  mynumber = Num2(8) mynumber.show() 

RESULT: 8

This is OK. But I replace Num2 with

class Num2(Num):     def __init__(self,num):         self.n2 = num*2     def show(self):         print self.n1,self.n2 

RESULT: Error. Num2 has no attribute "n1".

In this case, how can Num2 access n1?

like image 560
Yugo Kamo Avatar asked Mar 02 '11 10:03

Yugo Kamo


People also ask

What is __ init __ method in Python?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

What is inheritance in Python?

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.

What is __ init __( self in Python?

The self in keyword in Python is used to all the instances in a class. By using the self keyword, one can easily access all the instances defined within a class, including its methods and attributes. init. __init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor.

Do child classes need init?

Absolutely not. The typical pattern is that the child might have extra fields that need to be set that the parent does not have, but if you omit the __init__ method completely then it inherits it from the parent which is the correct behavior in your case.


1 Answers

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):     def __init__(self,num):         Num.__init__(self,num)         self.n2 = num*2 
like image 51
Mario Duarte Avatar answered Oct 14 '22 21:10

Mario Duarte