Python OOP之继承封装多态
面向对象的三大特征
- 继承
- 封装
- 多态
继承
- 子类可以使用父类定义的内容或者行为
- 继承的实现
-
父类,基类,超类,被继承的类,Base Class,Super Class
-
子类:有继承行为的类
-
所有类都必须有一个父类
- 如果没有,则默认为是object的子类
- 子类可以有多个父类
-
# 所有的类必须有父类
# 默认是object
class Pesron1():
pass
class Pesron2(object);
pass
class Person():
name = "NoName"
age = 0
# 父类写在类定义的时候的括号里
class Teacher(Person):
pass
t = Teacher()
print(t.name)
NoName
class Bird():
fly = "Yes, we can"
def flying(self):
print("飞呀飞呀")
class BirdMan(Person,Bird):
pass
bm = BirdMan()
bm.flying()
print(bm.name)
飞呀飞呀
NoName
issubclass监测两个类的父子关系
- 可以用来检测两个类的父子关系
# 利用刚才定义的BIrd,BirdMan,Person,Teacher,检测父子关系
print(issubclass(BirdMan,Bird))
print(issubclass(BirdMan,Person))
print(issubclass(BirdMan,Teacher))
True
True
False
help(issubclass)
Help on built-in function issubclass in module builtins:
issubclass(cls, class_or_tuple, /)
Return whether 'cls' is a derived from another class or is the same class.
A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
or ...`` etc.
构造函数
- 在函数实例化的时候调用的一个函数
- 自动调用
- 要求,第一个参数必须有,一般推荐self
- 构造函数的调用时间:一般认为在实例化的时候第一个被调用
- 一般速手动调用,实例化的时候调用,参数需要写入类名称后面的括号中
class Bird():
def __init__(self):
print("我被调用了")
# 此时被调用构造函数,实例化
b = Bird()
我被调用了
# 构造函数2
class Person():
def __init__(self,name,age):
print(name,age)
p = Person("yege",19)
yege 19
构造函数的继承
- 构造函数默认继承,子类如果没有构造函数,则自动调用父类的构造函数
- 一旦子类定义了构造函数,则不再自动调用父类构造函数
# 构造函数默认继承
class Person():
def __init__(self, name, age):
print("Person=({}, {})".format(name,age))
class Teacher(Person):
pass
t = Teacher("yege",10)
t = Teacher()
Person=(yege, 10)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-30-ac1b55e3c513> in <module>()
9
10 t = Teacher("yege",10)
---> 11 t = Teacher()
TypeError: __init__() missing 2 required positional arguments: 'name' and 'age'