一 python自动化基础能力:3.python基础上之数据类型,函数(19)


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)