一、继承
1、功能:继承提高了代码的复用性 ,让类与类之间产生了关系,有了这个关系,才有了多态的特性。
2、形式 class B(A):pass ,创建B类继承A
3、说明:1、在创建类的时候,如果我们省略父类则默认父类为object,所有类都继承object,object是所有类的父类。
class Animals(): def __init__(self,name): self._name = name def run(self): print('i can run ') class Cat(Animals): def scratch_mouse(self): print('i can catch jerry') c = Cat('tom') print('im %s'%c._name) c.run() c.scratch_mouse() im tom i can run i can catch jerry二、 重写
如果子类中有父类同名的方法,则通过子类的实例去调用该方法时,会调用子类的方法而不是父类的方法,这个特点也称为方法的重写(覆盖),就近原则。
class Animals(): def __init__(self,name): self._name = name def run(self): print('animals can run ') class Cat(Animals): def run(self): print('cat can run') def scratch_mouse(self): print('i can catch jerry') c = Cat('tom') print('im %s'%c._name) c.run() c.scratch_mouse() im tom cat can run i can catch jerry
三、 supper()方法
super()可以获得当前类的父类,通过super()返回对象调用父类方法时,不需要传递self。
一个错误:
class Animals(): def __init__(self,name): self._name = name def run(self): print('animals can run ') class Cat(Animals): def run(self): print('%s can run'%_name) def scratch_mouse(self): print('i can catch jerry') c = Cat('tom') print('im %s'%c._name) c.run() c.scratch_mouse() im tom File "C:/Users/yylwin10/Desktop/16.1 继承 重写.py", line 19, in <module> c.run() File "C:/Users/yylwin10/Desktop/16.1 继承 重写.py", line 11, in run print('%s can run'%_name) NameError: name '_name' is not defined原因:子类中看不到父类中的属性和方法!
解决方法1:
class Animals(): def __init__(self,name): self._name = name def run(self): print('animals can run ') class Cat(Animals): def run(self): print('%s can run'%c._name) def scratch_mouse(self): print('i can catch jerry') c = Cat('tom') print('im %s'%c._name) c.run() c.scratch_mouse()这样写虽然实现了功能,但是这样很不好。
方法二“:在父类中提供一个获取name的接口,在子类中利用super()方法获取父类。
class Animals(): def __init__(self,name): self._name = name def run(self): print('animals can run ') #@property def name(self): return self._name class Cat(Animals): def run(self): print('%s can run'%super().name()) def scratch_mouse(self): print('%s can catch jerry'%super().name()) c = Cat('tom') print('im %s'%c._name) c.run() c.scratch_mouse() im tom tom can run tom can catch jerry方法三:利用super在子类中调用父类的__init__ 方法。
class Animals(): def __init__(self,name): self._name = name def run(self): print('animals can run ') class Cat(Animals): def __init__(self,name): super().__init__(name) def run(self): print('%s can run'%self._name) c = Cat('tom') print('im %s'%c._name) c.run() im tom tom can run四、多重继承
Python中支持多重继承,也就是我们可以为一个类同时指定多个父类,开发时尽量不要用多重继承,原因是增加代码的复杂程度,如果多个父类中出现重名的方法,则会先在第一个父类中寻找,然后在找第二个,在找第三个,自己类中的方法会覆盖父类中的同名方法。__bases__ 方法,语法 类名.__bases__ 可以获取当前类所有的父类
class A(object): def text(self): print('A中的text方法') class B(object): def text(self): print('B中的text方法') def text2(self): print('B中的text2方法') class C(A,B): def text2(self): print('C中的text2方法') c = C() c.text() c.text2() print(C.__bases__) A中的text方法 C中的text2方法 (<class '__main__.A'>, <class '__main__.B'>)