python进阶——继承
三种类写法
# 经典类写法
class A: # 经典类:不由任何内置类型派生出来的类
pass
# 经典类
class Animal:
def walk(self):
print("走路。")
class Ani(Animal):
def walk(self):
print("走路。")
# 派生类
class Dog(Animal): # Dog类是派生类,有自己的属性或方法
def bite(self):
print("咬人。")
# 新式类:继承了object类或者该子类的是新式类,推荐使用
# object:对象,python为所有对象提供的基类(顶级父类),提供了一些内置的属性和方法,可以使用dir()查看
# python3中,如果一个类没有继承任何类,则默认继承object类,因此都是新式类
class A(object):
pass
print(dir(object))
多继承
# 子类可以拥有对个父类,并且具有所有福父类的属性和方法
class Father(object):
def money(self):
print("继承100万")
class Mother(object):
def apperance(self):
print("绝世容颜")
class Son(Father,Mother):
pass
s=Son()
s.money()
s.apperance()
多继承且父类方法中有同名的情况
# 不同父类存在同名的方法,调用写在前边的类。开发时需要尽量避免
class Father(object):
def money(self):
print("继承100万")
class Mother(object):
def money(self):
print("继承120万")
def apperance(self):
print("绝世容颜")
class Son(Mother,Father): # 方法同名,则按照就近原则,写在前边的优先调用
pass
s=Son()
s.money()
s.apperance()
# 方法的搜索顺序
print(Son.__mro__)
# 搜索方法时,会优先按照__mro__的输出结果,从左往右的顺序查找,找到就优先执行,不再搜索;搜索不到就报错
浙公网安备 33010602011771号