本文摘自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() # 再次调用父类的方法 - 获取属性值
|
以上代码执行结果如下:
阅读剩余部分
相关阅读 >>
使用Python开发简单的小游戏
Python实现逆序输出字符串
Python中有哪些基本数据类型
Python中flag什么意思
Python实现对自定义类对象排序(利用attrgetter)
使用Python画图怎么设置渐变色
Python能做什么项目
Python哪一年正式发布
Python单引号、双引号、三引号的区别
怎么对numpy里数组元素赋统一的值
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 如何让Python继承多个类?一文读懂Python类的继承