Python 类的继承实例详解

yipeiwu_com5年前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 
..... 

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

相关文章

Python 实现数组相减示例

问题描述: 有2个数组如下 a = [3,3,3,4,4,4,5,6,7] b = [3,3,4,4] 第1题:从数组a中删除所有在数组b中出现过的元素。对于上例来说,a删除结束...

django query模块

最近在接触一个Django项目,使用的是fbv( function-base views )模式,看起来特别不舒服,项目中有一个模型类117个字段,看我的有点晕,不过还是得干呀,生活呀,...

Python操作SQLite简明教程

一、SQLite简介 SQLite是一个包含在C库中的轻量级数据库。它并不需要独立的维护进程,并且允许使用非标准变体(nonstandard variant)的SQL查询语句来访问数据库...

Python中使用中文的方法

先来看看python的版本: >>> import sys >>> sys.version '2.5.1 (r251:54863, Apr...

python 获取等间隔的数组实例

可以使用numpy中的linspace函数 np.linspace(start, stop, num, endpoint, retstep, dtype) #start和stop为起...