在前文中已经提到了函数、类、方法的一些概念,那么从面向对象的视角来看看“继承”和“多态”的特性
class Father:def __init__(self):print('父类的构造方法被调用了')@staticmethoddef invoke():print('父类方法被调用')class Son1(Father):def __init__(self):print('子类Son1的构造方法被调用了') # 提示的Call to __init__ of super class is missedclass Son2(Father):def __init__(self):super().__init__()@staticmethoddef invoke():print('子类Son2方法被调用')if __name__ == '__main__':f = Father()f.invoke()print('--------------------')s1 = Son1()s1.invoke()print('--------------------')s2 = Son2()s2.invoke()# 输出结果如下:## 父类的构造方法被调用了# 父类方法被调用# --------------------# 子类Son1的构造方法被调用了# 父类方法被调用# --------------------# 父类的构造方法被调用了# 子类Son2方法被调用
关于 Call to __init__ of super class is missed 的影响
class Animal:def __init__(self):self.color = 'black'def eat(self):print('eating.......')class Cat(Animal):def __init__(self):self.age = 1if __name__ == '__main__':ci = Cat()ci.eat()print(ci.color, ci.age)# 输出结果如下:## eating.......# 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)
