Python 类的继承实例详解

yipeiwu_com6年前Python基础

Python 类的继承详解

Python既然是面向对象的,当然支持类的继承,Python实现类的继承比JavaScript简单。

Parent类:

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 Child(Parent): 
 
  def __init__(self): 
    print("child init") 
 
  def childMethod(self): 
    print("childMethod") 

调用

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

输出:

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

Python支持多继承

class A:    # 定义类 A 
..... 
 
class B:     # 定义类 B 
..... 
 
class C(A, B):  # 继承类 A 和 B 
..... 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

Django框架用户注销功能实现方法分析

本文实例讲述了Django框架用户注销功能实现方法。分享给大家供大家参考,具体如下: HttpResponse()里有个delete_cookie()方法专门用来删除cookie 我们到...

python使用post提交数据到远程url的方法

本文实例讲述了python使用post提交数据到远程url的方法。分享给大家供大家参考。具体如下: import sys, urllib2, urllib zipcode = "S2...

在python中利用numpy求解多项式以及多项式拟合的方法

构建一个二阶多项式:x^2 - 4x + 3 多项式求解 >>> p = np.poly1d([1,-4,3]) #二阶多项式系数 >>> p...

django迁移数据库错误问题解决

django.db.migrations.graph.NodeNotFoundError: Migration order.0002_auto_20181209_0031 depen...

python实现将文本转换成语音的方法

本文实例讲述了python将文本转换成语音的方法。分享给大家供大家参考。具体实现方法如下: # Text To Speech using SAPI (Windows) and Pyt...