本文摘自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的join怎么用
            
                        apache怎么支持Python
            
                        Python web看什么书
            
                        requests库怎么安装
            
                        Python怎样实现百度语音识别api的步奏详解
            
                        django基础教程总结
            
                        Python模拟微博登陆的方法介绍(附代码)
            
                        如何用Python统计不同字符个数
            
                        Python中注释一般为什么颜色
            
                        自学Python可以做什么兼职
            
                        更多相关阅读请进入《Python》频道 >>
            
 
                         人民邮电出版社
            python入门书籍,非常畅销,超高好评,python官方公认好书。
          转载请注明出处:木庄网络博客 » 如何让Python继承多个类?一文读懂Python类的继承