PHP前端开发

如何让Python继承多个类?

百变鹏仔 4小时前 #Python
文章标签 多个

面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过python类的继承并且在此基础上衍生出让python继承多个类的方法。

通过Python类的继承创建的新类称为子类派生类,被继承的类称为基类父类超类

继承语法:

class 派生类名(基类名)    ...

实例

#!/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免费学习笔记(深入)”;

调用子类构造方法调用子类方法调用父类方法父类属性 : 200

对类的继承的延伸:Python继承多个类

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

你可以使用issubclass()或者isinstance()方法来检测。

issubclass() - 布尔函数判断一个类是另一个类的子类或者子孙类,语法:issubclass(sub,sup)

isinstance(obj, Class) 布尔函数如果obj是Class类的实例对象或者是一个Class子类的实例对象则返回true。