本文摘自php中文网,作者Tomorin,侵删。
面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过Python类的继承并且在此基础上衍生出让Python继承多个类的方法。通过Python类的继承创建的新类称为子类或派生类,被继承的类称为基类、父类或超类。
继承语法:
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
class Parent: # 定义父类
parentAttr = 100
def __init__(self):
print "调用父类构造函数"
def parentMethod(self):
print '调用父类方法'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "父类属性 :" , Parent.parentAttr
class Child(Parent): # 定义子类
def __init__(self):
print "调用子类构造方法"
def childMethod(self):
print '调用子类方法'
c = Child() # 实例化子类
c.childMethod() # 调用子类的方法
c.parentMethod() # 调用父类方法
c.setAttr(200) # 再次调用父类的方法 - 设置属性值
c.getAttr() # 再次调用父类的方法 - 获取属性值
|
以上代码执行结果如下:
阅读剩余部分
相关阅读 >>
Python3终端按哪里跳出循环
linux怎么卸载Python?
Python有序列表以及方法的介绍(代码)
用turtle画个单身狗送给自己~
Python 通过字符串调用对象属性或方法
Python写错了怎么删除
对Python 2.7 pandas 中的read_excel详解
在Python3.x中可以使用中文作为变量名吗
序列分类、imdb影评分类等功能详解
Python中执行存储过程及获取返回值的方法介绍
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 如何让Python继承多个类?一文读懂Python类的继承