Home > Article > Backend Development > Python inheritance and object-oriented analysis
The Python programming language is a powerful development language, and its biggest feature is its simplicity and ease of use. It also has object-oriented features, which can help us achieve some specific functional requirements. We will introduce the related concepts of Python inheritance to you in detail here today.
The following code uses Python2.4. After installation, use idle's IDE development environment (it is said to be an IDE, which is much simpler than delphi, VS.net, etc.)
Create a .py file from the File-New menu and write Python inheritance code below:
>>> ============= RESTART ===============
>>> class SuperClass: 1.def sample(self):
print 'SuperClass'
2.class SubClass(SuperClass):
pass
3.sub = SubClass()
4.sub.sample()
You need to save it first, and then Press F5 to execute. The main window of idle displays:
The subclass has called the sample method of the parent class. Now modify the code as follows:
class SuperClass: 1.def sample(self):
print 'SuperClass'
2.class SuperClass1:
def sample(self):
3.print 'SuperClass1'
class SubClass(SuperClass,SuperClass1):
4.pass
sub = SubClass()
5.sub.sample()
Run Python inheritance code, The result you see is the same as above. The sample method of the first parent class is called by the subclass here, but the sample method of the second parent class is not called. Now you know what to say next. Change the declaration of the SubClass class. Into:
class SubClass(SuperClass1, SuperClass): 1. Pass
run, and the result you see is that the sample method of SuperClass1 is called.
>>> ============= RESTART =============== 1.>>>
SuperClass1
2. >>>
At this point, you can see that in the case of Python inheritance, the same method in the parent class will call the first parent class method declared by the class in the child class.
The above is the content of Python inheritance and object-oriented analysis. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!