Python的高级特性12:类的继承
在面向对象的程序设计中,继承(Inheritance)允许子类从父类那里获得属性和方法,同时子类可以添加或者重载其父类中的任何方法。在C++和Java的对象模型中,子类的构造函数会自动调用父类的构造函数,但在Python中却不是这样,你必须在子类中显示调用父类的构造函数。
In [1]: class Employee: ...: def __init__(self,name,salary=0): ...: self.name = name ...: self.salary = salary ...: In [2]: class Designer(Employee): def __init__(self,name): ...: self.name = name ...: In [3]: d = Designer("alex") In [4]: d.salary --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-4-c8934453b0a8> in <module>() ----> 1 d.salary AttributeError: 'Designer' object has no attribute 'salary' In [5]: e = Employee('alex') In [6]: e.salary Out[6]: 0
可以看出子类Designer没有继承父类的初始化函数,如果需要继承,则需要加上:Employee.__init__(self, name, 5000).