ToB企服应用市场:ToB评测及商务社交产业平台

标题: python学习笔记:继承与超类 [打印本页]

作者: 丝    时间: 2023-7-12 12:22
标题: python学习笔记:继承与超类
与java类似,继承的出现是为了提高代码的重复利用率,避免多次输入同样的代码。而超类就是java中的父类。
1.继承

要指定超类,可在定义类时,在class语句中的类名后加上超类名
格式
  1. class Dog:   #
  2.         pass
  3. class Bobo(Dog):  # Dog类的子类
  4.         pass
复制代码
子类会
  1. class Dog:
  2.     def __init__(self):
  3.         print('wang!!!')
  4.    
  5.     def eat(self):
  6.         print('Dog is eating.')
  7.    
  8. class Bobo(Dog):  # 继承Dog
  9.     pass
  10. tom = Bobo()
  11. tom.eat()
  12. >
  13. wang!!!
  14. Dog is eating.
复制代码
在子类中进行重写
  1. class Dog:
  2.     def __init__(self):
  3.         print('wang!!!')
  4.    
  5.     def eat(self):
  6.         print('Dog is eating.')
  7.    
  8. class Bobo(Dog):
  9.     def __init__(self):
  10.         print('Bobo is wang!')
  11.     def eat(self):
  12.         print('Bobo is eating.')
  13. tom = Bobo()
  14. tom.eat()
  15. >
  16. Bobo is wang!
  17. Bobo is eating.
复制代码
1.1查找一个类的子类和基类

  1. issubclass(Bobo, Dog)  # 子类 超类
  2. > True
  3. issubclass(Dog, Bobo)
  4. > False
复制代码
  1. print(Bobo.__bases__)
  2. > (<class '__main__.Dog'>,)
复制代码
  1. class Dog:
  2.     pass
  3.    
  4. class Bobo(Dog):
  5.     pass
  6. tom = Bobo()
  7. print(isinstance(tom, Bobo))
  8. print(isinstance(tom, Dog))
  9. >
  10. True
  11. True
复制代码
  1. print(tom.__class__)
  2. > <class '__main__.Bobo'>
复制代码
1.2 多个超类

尽量避免使用
格式
  1. class A:
  2.         pass
  3. class B:
  4.         pass
  5. class C(A, B):  # 同时继承A和B
  6.         pass
复制代码
1.3接口

接口这一概念与多态相关。实际上,python中没有与java相对应的接口。需要特定的模块来实现
1.4 抽象基类

抽象类不能(不应该)被实例化,用于定义子类应该实现的一些抽象方法。
格式
  1. from abc import ABC, abstractmethod
  2. class 类名(ABC):  # 继承ABC类
  3.         @abstractmethod   # 标记为抽象方法,在子类中必须实现
  4.         def 方法名(self):
  5.                 pass
复制代码
  1. from abc import ABC, abstractmethod
  2. class Dog(ABC):
  3.     @abstractmethod
  4.     def eat(self):
  5.         pass
  6.    
  7. class Bobo(Dog):
  8.     def eat(self):
  9.         print('eating.')
  10. tom = Bobo()
  11. tom.eat()
  12. > eating.
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4