12.1 类的继承
- 在python中,父类和子类(派生类)只有在继承的时候会产生。
- 继承为了拿到父类的属性和方法
#定义父类
class Parent_Foo():
def __init__(self,first_name,money,car,house):
self.first_name=first_name
self.money=money
self.car=car
self.house=house
def heritage(self):
print(f'继承{self.first_name}先生的其他财产')
#子类
class Son_Foo(Parent_Foo): #继承只需要在子类中传入父类名
pass
sf=Son_Foo('zhang',4500000,'car1','big_house')
print(sf.first_name)
print(sf.money)
sf.heritage()
#输出
zhang
4500000
继承zhang先生的其他财产
- 为什么要用继承?
- 减少代码冗余,所有的父亲都可以用这个类,减轻复杂度。
- 猫是动物,狗也是动物。因此动物是父类,猫和狗是子类。
#父类
class Animal():
def __init__(self,height,weight):
self.height=height
self.weight=weight
def say_hi(self):
print(self.__class__.__name__,'hi')
#子类
class XingXing():
def sleep(self):
print('sleep')
#子类
class People(Animal,XingXing): #可继承多个
def read(self):
print('read')
def sleep(self):
print(f'self_sleep') #优先使用自己的方法
mike=People(168,120)
#通过对象mike可以使用父类'Animal'方法'say_hi',父类'XingXing'方法'sleep'和使用自己的方法'read'
mike.say_hi()
mike.read()
mike.sleep()
#输出
People hi
read
self_sleep
- 不推荐使用继承,因为会非常乱,继承多个父类,功能与功能之间会混。顶多继承一个。
- 继承后查找顺序,先自己,再自己所在的类,再父类在,再父类的父类。