上一篇介绍了Python中类相关的一些基本点,本文看看Python中类的继承和__slots__属性。
在Python中,同时支持单继承与多继承,一般语法如下:
| 12 | class SubClassName(ParentClass1 [, ParentClass2, ...]): class_suite |
实现继承之后,子类将继承父类的属性,也可以使用内建函数insubclass()来判断一个类是不是另一个类的子孙类:
| 123456789101112131415161718192021222324252627 | class Parent(object): \’\’\’ parent class \’\’\’ numList = [] def numAdd(self, a, b): return a+b class Child(Parent): pass c = Child() # subclass will inherit attributes from parent class Child.numList.extend(range(10))print Child.numListprint \”2 + 5 =\”, c.numAdd(2, 5) # built-in function issubclass() print issubclass(Child, Parent)print issubclass(Child, object) # __bases__ can show all the parent classesprint Child.__bases__ # doc string will not be inheritedprint Parent.__doc__print Child.__doc__ |
代码的输出为,例子中唯一特别的地方是文档字符串。文档字符串对于类,函数/方法,以及模块来说是唯一的,也就是说__doc__属性是不能从父类中继承来的。

继承中的__init__
当在Python中出现继承的情况时,一定要注意初始化函数__init__的行为。
1. 如果子类没有定义自己的初始化函数,父类的初始化函数会被默认调用;但是如果要实例化子类的对象,则只能传入父类的初始化函数对应的参数,否则会出错。
| 123456789101112 | class Parent(object): def __init__(self, data): self.data = data print \”create an instance of:\”, self.__class__.__name__ print \”data attribute is:\”, self.data class Child(Parent): pass c = Child(\”init Child\”) print c = Child() |
代码的输出为:

2. 如果子类定义了自己的初始化函数,而没有显示调用父类的初始化函数,则父类的属性不会被初始化
| 123456789101112 | class Parent(object): def __init__(self, data): self.data = data print \”create an instance of:\”, self.__class__.__name__ print \”data attribute is:\”, self.data class Child(Parent): def __init__(self): print \”call __init__ from Child class\” c = Child() print c.data |
代码的输出为:

3. 如果子类定义了自己的初始化函数,显示调用父类,子类和父类的属性都会被初始化
| 12 class=\”crayon-table\”> | |||||||||
12rayon-font-monaco crayon-os-pc print-yes notranslate\” data-settings=\” minimize scroll-always\” style=\” margin-top: 12px; margin-bottom: 12px; font-size: 13px !important; line-height: 15px !important;\”>
实现继承之后,子类将继承父类的属性,也可以使用内建函数insubclass()来判断一个类是不是另一个类的子孙类:
代码的输出为,例子中唯一特别的地方是文档字符串。文档字符串对于类,函数/方法,以及模块来说是唯一的,也就是说__doc__属性是不能从父类中继承来的。
继承中的__init__ 当在Python中出现继承的情况时,一定要注意初始化函数__init__的行为。 1. 如果子类没有定义自己的初始化函数,父类的初始化函数会被默认调用;但是如果要实例化子类的对象,则只能传入父类的初始化函数对应的参数,否则会出错。
代码的输出为:
2. 如果子类定义了自己的初始化函数,而没有显示调用父类的初始化函数,则父类的属性不会被初始化
代码的输出为:
3. 如果子类定义了自己的初始化函数,显示调用父类,子类和父类的属性都会被初始化
|