Detailed explanation of Python class inheritance example code

高洛峰
Release: 2017-03-26 09:44:39
Original
1582 people have browsed it

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)
Copy after login

Child class

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

Call

p1 = Parent(); 
p1.parentMethod(); 
 
c1 = Child(); 
c1.childMethod();
Copy after login

Output:

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

Python supports multiple inheritance

class A:    # 定义类 A 
..... 
 
class B:     # 定义类 B 
..... 
 
class C(A, B):  # 继承类 A 和 B 
.....
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!