class Animal:def run(self):print('Running...')def sleep(self):print('Sleeping...')class Dog(Animal):def run(self):print('Dog is running...')def sleep(self):print('Dog is sleeping...')def Housekeep(self):print('Dog is housekeeping')d = Dog()d.run()
打印Dog is ...
下边再详细说明,
class A(object):def test(self):print('A...')class B(A):passclass C(B):passc = C()c.test()
打印A... 。
类B中加入方法test()后,
class A(object):def test(self):print('A...')class B(A):def test(self):print('B...')class C(B):passc = C()c.test()
打印B...
类C中加入方法test()后,
class A(object):def test(self):print('A...')class B(A):def test(self):print('B...')class C(B):def test(self):print('C...')c = C()c.test()
打印C... 。
当我们调用一个对象时,会有先去当前对象寻找是否有该方法,如果有直接调用;如果没有,则取当前对象的父类中寻找,如果有,直接调用父类中的方法,如果没有,则去父类的父类寻找,如果有直接调用,以此类推,直到找到,如果依然没有则报错 。
10.4 super()
父类中所有的方法都会被子类继承,包括特殊方法,如()等,也可以重写特殊方法 。
class Animal:def __init__(self,name):self._name = namedef run(self):print('Running...')def sleep(self):print('Sleeping...')@propertydef name(self):return self._name@name.setterdef name(self,name):self._name = nameclass Dog(Animal):def run(self):print('Dog is running...')def sleep(self):print('Dog is sleeping...')def Housekeep(self):print('Dog is housekeeping')d = Dog()d.run()
会抛出异常,: ()1: 'name'
因为初始化没有传入参数,因为父类初始化要传入name这个参数,子类也必须传入 。
传入参数后,
class Animal:def __init__(self,name):self._name = namedef run(self):print('Running...')def sleep(self):print('Sleeping...')@propertydef name(self):return self._name@name.setterdef name(self,name):self._name = nameclass Dog(Animal):def run(self):print('Dog is running...')def sleep(self):print('Dog is sleeping...')def Housekeep(self):print('Dog is housekeeping')d = Dog('erha')print(d.name)
打印erha
调用方法修改属性,
class Animal:def __init__(self,name):self._name = namedef run(self):print('Running...')def sleep(self):print('Sleeping...')@propertydef name(self):return self._name@name.setterdef name(self,name):self._name = nameclass Dog(Animal):def run(self):print('Dog is running...')def sleep(self):print('Dog is sleeping...')def Housekeep(self):print('Dog is housekeeping')d = Dog('erha')d.name = 'demu'print(d.name)
打印demu 。
如果需要在子类中定义新的属性时,即要扩展属性时,
class Animal:def __init__(self,name):self._name = namedef run(self):print('Running...')def sleep(self):print('Sleeping...')@propertydef name(self):return self._name@name.setterdef name(self,name):self._name = nameclass Dog(Animal):def __init__(self,name,age):self._name = nameself._age = agedef run(self):print('Dog is running...')def sleep(self):print('Dog is sleeping...')def Housekeep(self):print('Dog is housekeeping')@propertydef age(self):return self._age@age.setterdef age(self, age):self._age = aged = Dog('erha',10)print(d.name)print(d.age)
- 最神秘的三座陵墓,一座不能挖,一座不敢挖,另一座挖不动
- 明明是一代传奇词人,偏偏无奈生在帝王家
- 一个开创出了盛世,同时也是历史上最大的败家子的帝王
- 宋仁宗:历史上最宽仁的皇帝之一却也难过美人关
- 一条杆棒等身齐:揭开太祖赵匡胤的武功有多高
- 乾隆皇帝一生最大的过错是什么?他为何这样做
- 三国十大家门不幸的美女:最后一个让人脊背发凉
- 【地图学】二、地图矢量化
- 【批量改文件夹中的图片名称-python】
- 60升电热水器功率一般多大