在前文中已经提到了函数、类、方法的一些概念,那么从面向对象的视角来看看“继承”和“多态”的特性

  1. class Father:
  2. def __init__(self):
  3. print('父类的构造方法被调用了')
  4. @staticmethod
  5. def invoke():
  6. print('父类方法被调用')
  7. class Son1(Father):
  8. def __init__(self):
  9. print('子类Son1的构造方法被调用了') # 提示的Call to __init__ of super class is missed
  10. class Son2(Father):
  11. def __init__(self):
  12. super().__init__()
  13. @staticmethod
  14. def invoke():
  15. print('子类Son2方法被调用')
  16. if __name__ == '__main__':
  17. f = Father()
  18. f.invoke()
  19. print('--------------------')
  20. s1 = Son1()
  21. s1.invoke()
  22. print('--------------------')
  23. s2 = Son2()
  24. s2.invoke()
  25. # 输出结果如下:
  26. #
  27. # 父类的构造方法被调用了
  28. # 父类方法被调用
  29. # --------------------
  30. # 子类Son1的构造方法被调用了
  31. # 父类方法被调用
  32. # --------------------
  33. # 父类的构造方法被调用了
  34. # 子类Son2方法被调用

关于 Call to __init__ of super class is missed 的影响

详细的参考文档 https://blog.caoyu.info/super-init-in-python.html

  1. class Animal:
  2. def __init__(self):
  3. self.color = 'black'
  4. def eat(self):
  5. print('eating.......')
  6. class Cat(Animal):
  7. def __init__(self):
  8. self.age = 1
  9. if __name__ == '__main__':
  10. ci = Cat()
  11. ci.eat()
  12. print(ci.color, ci.age)
  13. # 输出结果如下:
  14. #
  15. # eating.......
  16. # AttributeError: 'Cat' object has no attribute 'color'

  • 判断一个类是否为另一个类的子类 issubclass
  • 判断对象是否为特定类的实例 isinstance ```python isinstance(“hi”,str)

输出 True

```

  • 查询具体类所属的基类 __bases__
  • 查询具体对象所属的类 __class__ ```python “hi”.class

输出

```

  • 查询对象中存储的所有值 __dict__

  • 查询对外暴露的方法和属性。hasattr, setattr, getattr

    反射的库可见 import inspect

  • 判断对象是否可调用 callable(object)

  • 返回对象的类型 type(object)