Inheritance in Python - ProgrammerTech
Language:

Search

Inheritance in Python

  • Share this:
Inheritance in Python

Inheritance Python

Inheritance means that one class inherits another class that takes all the method in the other class. For example, we want to make a new class and inherit the class in our previous example.

The word inherit means to include the content of a class in another class in Python. A class can inherit from another class until it obtains the functions and variables in it. So the idea of ​​heredity is simple, but its usefulness is very strong. For example, if you want to create a new class and notice that there is a ready-made class that contains codes that may be useful to you, you can use them instead of writing them from scratch, that is, you can make the class that you defined inherit this class, and then you can use all the variables and functions that the new class inherited from the class ready made.

The class that inherits from another class is called the son class, and it is also called the subclass, and it is also called (Derived Class, Extended Class or Child Class), and the more common one is said to be Child’s son, but the class that bequeaths what it has to another class is called the father class and is called Superclass And it is called (Base Class or Parent Class).

Inheritance is, as is the custom in the field, that the son inherits some traits from his father or from his mother some traits. In the same matter we have in object oriented programming in the concept of inheritance, which is that a class inherits from another class so that the inherited class is called The son and the inherited class are called the father so that the son can access all the functions and variables in the father class and reuse them again.

And we benefit from inheritance is to shorten the code. Instead of rebuilding the function again, if the function exists in the parent class, we can reuse it again instead of building it and consuming memory and prolonging the code so that the program is organized and beautiful.

Syntax inheritance

class BaseClass:
    Body class
class Derivative class(BaseClass):
        Derived class body

 

Create a parent class in Python

Any class can be a parent, the syntax is the same as creating any other class.

class Info:
    def __init__ (self, name = "Muhammad Alush", age = 28):
        self.name = name
        self.age = age
    def my_info (self,data = "My Info"):
        print ("I am Programmer")
        print (data)
c = Info ("Muhammad", "26")
c.my_info ("data : ")
print (c.name)
print (c.age)

 

Create a child class in Python

To create a child class that inherits the function from another class, the main class must be sent as a parameter when creating a child class.

class another_user(user):
    pass

The class called user will have the same properties and methods as another_user and the pass word is used when we don't want to add any functions or properties to the class.

 

Inheritance forms in Python

In Python there are 4 forms of inheritance:

  1. Single inheritance is that a class inherits from only one class.
  2. Multi level inheritance means that a class inherits from one class, and this class was originally inherited from another class.
  3. Multiple inheritance means that a class inherits from more than one class.
  4. Hierarchical inheritance means that a class is inherited by more than one class.

 

Example 1

We will write two classes, namely Info and Info2, and the new class, Info2, inherits everything in the Info class.

class Info2 (Info):
   def mydata (self):
      print ("hello man")
c = Info2()
print (c.age)
print (c.name)
c.my_info()
c.mydata()

We created a son class which is Info2, and this son inherited from the father class Info, and inside this class there is a function which is mydata, then we created an object c and all the functions in the object c were called.

If we run, we will get the following result

21
kaissar
hello world man
my data
kaissar
hello man 

Example 2

Create a class in Cs with first and last name properties in Python, use the printname method.

class Cs:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname
def printname(self):
    print(self.firstname, self.lastname)

Use the Cs class to create an object and then print the name.

x = Cs("Saja", "Osman")
x.printname()

And create a class in the name of the student that will inherit the properties and methods from the Cs class.

class Student(Cs):
    pass

 

Single Inheritance Python

Single inheritance When a single class inherits from only one parent or the class inherits from one class, this is called single inheritance.

Example 1

The first file is A.py

class A:
    x = 15
    def print_msg(self):
        print('Hello from class A')

We created a class named A and inside this class there is a variable x and its value is 15 and there is a function named print_msg and this function prints a specific task.

The second file is B.py

from A import A
class B(A):
    y = 25

We have included or called the class A in the file A.py in order to be able to inherit from it and we created a class named B and this class inherits from A and this class contains a variable y value of 25.

The third file is Test.py

from B import B
b = B()
print('y:', b.y)
print('x:', b.x)
b.print_msg()

We called class B from the file B.py so that we can create an object from this class, and we created the object b from class B and we printed the value of the variable y in the object b that we defined in class B, and then we printed the value of the variable x in the object b that he inherited from class B from class A.

Then we called the function print_msg() which is in object b and inherited from class B from A.

When we run we will get the result

y: 25
x: 15
Hello from class A

Example 2

We will create two files, the first one is the parent and we will call it main. The second is the son and we call it index.

main.py

#file main.py
class Human:
    '''this class for human'''
    skin_color = 'black'
    hair_color = 'black'
    eye_color  = 'blue'
    def print_skin_color(self):
        return "your skin color is {}".format(self.skin_color)
    def print_hair_color(self):
        return f"my hair color is {self.hair_color}"
    def print_eye_color(self):
        return f"my eye color {self.eye_color}"

We created a class in the name of Human, which is the father class, then we created several characteristics or characteristics for it, which are skin color, hair color and eye color. Then we gave it some functions which is print_skin_color and this method returns the skin color and we format the process by using the format. The second function is to print the color of hair and the third function is to print the color of the eyes.

index.py

#file index.py
from main import Human
class Person(Human):
    pass
app = Person()
result = app.print_eye_color()
print(result)

We wrote from in order to call the library, i.e. the main file, bring me the human class. Then we created the son class with the name Person and inherited it from the human class and set the pass to not add anything to it. Then we consider that the father is dead and we created an app object and set it as Person and created a variable result. Then the son was able to access the attribute that the father inherited to him, which is print_eye_color and the same thing will be able to access everything in the father, then we print the variable result. When we run this code, we will see the following result:

my eye color blue

 

Multi level Inheritance in Python

Multi level inheritance means when a class inherits from multiple classes, or in a more correct sense, a class inherits from more than one class.

Example 1

class Base(object): 
    #Constructor
	def __init__(self, name): 
		self.name = name 
    #Name
	def Name(self): 
		return self.name  
class Child(Base): 
	#Constructor 
	def __init__(self, name, age): 
		Base.__init__(self, name) 
		self.age = age 
    #age
	def Age(self): 
		return self.age 
class GrandChild(Child): 
	#Constructor 
	def __init__(self, name, age, address): 
		Child.__init__(self, name, age) 
		self.address = address 
    #address
	def Address(self): 
		return self.address		 
g = GrandChild("Saja", 27, "Sudan") 
print(g.Name(), g.Age(), g.Address())

A grandfather class was created, which is Base, and it includes the name and a father class with the name Chile, and this class included the age, and the last class is the grandson. He had three properties, one of them from his father, the other from his grandfather, and the last of them was his. And when executing the previous code

Saja 27 Sudan

Example 2

The first file is A.py

class A:
    def print_a(self):
        print('Hello from class A')

We have defined a class A and this class contains a print_a() function.

The second file is B.py

from A import A
class B(A):
    def print_b(self):
        print('Hello from class B')

We called or included the class A in the file A.py so that we could inherit from it, and we created class B that inherits from class A and created the print_b() function.

The third file is C.py

from B import B
class C(B):
    def print_c(self):
        print('Hello from class C')

We included the existing class B in the file B.py and created a new class which is C and inherited this new class from B and created the print_c function.

Fourth file Test.py

from C import C
c = C()
c.print_a()
c.print_b()
c.print_c()

Here we included the C class in the file C.py and created an object c from the C class and then called all the functions in the c object.

When you run the code, we will get the result

Hello from class A
Hello from class B
Hello from class C

 

Multiple Inheritance Python

Multiple inheritance means when we have several species such as grandfather, father and grandson. It means that the class will inherit from more than one class.

Example 1

class Saja(object): 
	def __init__(self): 
		self.str1 = "Curious"
		print("Saja") 
class Muhammad(object): 
	def __init__(self): 
		self.str2 = "Crazy"		
		print("Muhammad") 
class Derive(Saja, Muhammad): 
	def __init__(self): 
		Saja.__init__(self) 
		Muhammad.__init__(self) 
		print("Derive") 
	def printStrs(self): 
		print(self.str1, self.str2) 
ob = Derive() 
ob.printStrs()

We created a first class, Saja, and added __init__ in order to add properties to this class, and we added the property Curious to it, meaning it is curious. By derivation of Klas Ibn inherits from parents Saja and Muhammad. When we run this code, we will see the following result:

Saja
Muhammad
Derive
Curious Crazy

We also noticed that the name of the first class was printed for us, followed by a new line, the name of the second class, and they are the parents, and below them, the son was printed for us and the characteristics he took from the parents, namely curiosity and madness.

Example 2

The first file is A.py

class A:
    def print_a(self):
        print('Hello from class A')

We created class A and set a function print_a.

The second file is B.py

class B:
    def print_b(self):
        print('Hello from class B')

We have created class B and in this class the print_b function.

The third file is C.py

from A import A
from B import B
class C(A, B):
    def print_c(self):
        print('Hello from class C')

We included the class A in the file A.py and we also included the class B in the file B.py, and we created a class C that inherits from classes A and B and there is a function print_c.

Fourth file Test.py

from C import C
c = C()
c.print_a()
c.print_b()
c.print_c()

We include the C class in the C.py file, then create an object c from the C class, and then call all the functions in the c object.

When we run the code we will get the result.

Hello from class A
Hello from class B
Hello from class C

 

hierarchical inheritance in Python

Hierarchical inheritance means the creation of more than one class from one base, or more correctly, this class is inherited from more than one class.

Example 1

#basic class
class MyWebsite:
    def programmer(self, name):
        self.name = name
        print(f'{self.name} Is Programming')
#Subclass1
class MuhammadAlush(MyWebsite):
    pass
#Subclass2
class AhmedKaissar(MyWebsite):
    pass
data = MuhammadAlush()
data.programmer("MuhammadAlush")
ahmed = AhmedKaissar()
ahmed.programmer("AhmedKaissar")
#There is no relationship between subclass1 and subclass2

We have a basic class, which is MyWebsite, and it has a progammer function and two subclasses, which are Muhammad Alush and the other class AhmedKaissar, but as we can see, there is no relationship between the two subclasses and they inherited from the father that they are programmers. And when you run the previous code, the result will be:

MuhammadAlush Is Programming
AhmedKaissar Is Programming

Example 2

The first file is A.py

class A:
    def print_a(self):
        print('Hello from class A')

We created class A and inside the class there is a function print_a.

The second file is B.py

from A import A
class B(A):
    def print_b(self):
        print('Hello from class B')

We included class A from the file A.py, created class B, inherited from class A, and created the print_b function.

The third file is C.py

from A import A
class C(A):
    def print_c(self):
        print('Hello from class C')

We included the class A in the file A.py and created a class C that inherits from class A and contains the print_c function.

Fourth file Test.py

from B import B
from C import C
c = C()
c.print_a()
c.print_c()
b = B()
b.print_a()
b.print_b()

We included the class B in the file B.py and the class C in the file C.py and we created an object c from class C and called all the functions in it, then we created an object b from class B and called all the functions in it.

When you run the code, the result will be

Hello from class A
Hello from class C
Hello from class A
Hello from class B

 

Hybrid inheritance

This type is a combination of more than one type of genetics

Example

class AdminWebsite:
	def func1(self):
		print("This function is Main.")
class MuhammedAlush(AdminWebsite):
	def func2(self):
		print("This function is MuhammadAlush. ")
class AhmadKaissar(AdminWebsite):
	def func3(self):
		print("This function is AhmedKaissar.")
class SajaAlsadig(MuhammedAlush, AdminWebsite):
	def func4(self):
		print("This function is SajaAlsadig.")
# Driver's code
object = SajaAlsadig()
object.func1()
object.func2()

And when you run the above code

This function is Main.
This function is MuhammadAlush.

When a class inherits more than a class, there is a very high possibility that it will inherit properties and functions that have the same name, and therefore there will be a conflict in these names. It causes a logical error in the desired result.

And if you want to create a class and want to ensure that there are no problems with name collision when inheriting this class, then you can adopt the principle of data hiding when naming variables and functions, and the idea of ​​hiding data is to make the programmer able to Putting the same names of variables and functions in the father and son classes, with the guarantee that no conflict will occur. You can simply put the __ symbol at the beginning of the variable or function name to be able to use the same name in the classes it inherits from and then the Python interpreter will differentiate between the things in the parent and child classes.


Tags:
Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com