Home  >  Article  >  Backend Development  >  Detailed explanation of Python class inheritance example code

Detailed explanation of Python class inheritance example code

高洛峰
高洛峰Original
2017-03-26 09:44:391617browse

This article mainly introduces the Inheritance of the Python class and the relevant information on detailed examples. Friends in need can refer to

Inheritance of the Python class Detailed explanation

Since Python is

object-oriented, of course it supports class inheritance. Python implements class inheritance simpler thanJavascript.

Parent class:

class Parent: 
 
  parentAttr = 100 
 
  def init(self): 
    print("parent Init") 
 
  def parentMethod(self): 
    print("parentMethod") 
   
  def setAttr(self,attr): 
    self.parentAttr = attr 
 
  def getAttr(self): 
    print("ParentAttr:",Parent.parentAttr)

Child class

class Child(Parent): 
 
  def init(self): 
    print("child init") 
 
  def childMethod(self): 
    print("childMethod")

Call

p1 = Parent(); 
p1.parentMethod(); 
 
c1 = Child(); 
c1.childMethod();

Output:

parent Init 
parentMethod 
child init 
childMethod 
Press any key to continue . . .

Python supports multiple inheritance

class A:    # 定义类 A 
..... 
 
class B:     # 定义类 B 
..... 
 
class C(A, B):  # 继承类 A 和 B 
.....
Thank you for reading, I hope it can help everyone, thank you for your support of this site!

The above is the detailed content of Detailed explanation of Python class inheritance example code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn