函數的重寫
前提:在具有繼承關系的類中
作用:將父類中已有的函數在子類中進行重新的實現【聲明部分一樣的,實現部分不一樣】
1.系統函數的重寫
注意:並不是所有的函數都需要重寫
__str__
__repr__
代碼如下:
class Person(object): def __init__(self,name,age,height,score): self.name = name self.age = age self.height = height self.score = score #3.__str__的重寫:返回一個對象信息的字符串 def __str__(self): return "name=%s age=%d height=%f score=%d" % (self.name,self.age,self.height,self.score) """ def __repr__(self): return "hello" """ #4.str和repr都和對象有關,讓二者的實現返回相同的結果, __repr__ = __str__可以省略 __repr__ = __str__ #等價於下面的寫法: """ def __repr__(self): return "name=%s age=%d height=%f score=%d" % (self.name,self.age,self.height,self.score) """ p1 = Person("abc",19,17,37) print(p1.name,p1.score,p1.age,p1.height) #1.如果直接打印對象,獲取的是對象的地址 print(p1) #<__main__.Person object at 0x000001C7E4190DD8> p2 = Person("abc",19,17,37) print(p2.name,p2.score,p2.age,p2.height) #2.函數的重寫: # __str__:返回一個字符串,但是,如果沒有重寫該函數,默認返回該對象的地址 #當重寫了__str__之后,直接使用對象,則返回的是str函數中的返回值 #print(p1.__str__()) """ 總結: a.當str和repr都未被重寫的時候,使用對象,調用的是str,此時的str返回的是對象的地址 b.當str和repr都被重寫之后,使用對象,調用的是str,返回的是指定的字符串 c.當沒有重寫str,但是,重寫repr,使用對象,調用的是repr,返回的是指定的字符串 d.當只重寫了str,調用是str """ #優點或者使用場景:當一個對象的屬性很多,並且都需要通過打印來查看相應的值,就可以重寫str函數,簡化代碼 p3 = Person("abc",19,17,37) print(p3)
2.自定義函數的重寫
函數重寫的時機:當父類中的函數的功能不滿足子類的的需求時,就需要重寫
重寫的規則;子類中出現和父類中重名的函數,則子類中的會覆蓋掉父類中
代碼演示:
#父類 class Animal(object): def __init__(self,name): self.name = name def show(self): print("父類~~show") #子類 class Dog(Animal): def __init__(self,name): super().__init__(name) class Cat(Animal): def __init__(self,name): super().__init__(name) class Tiger(Animal): def __init__(self,name): super().__init__(name) #重寫父類中的函數 #聲明相同,實現不同的 def show(self,num): #調用父類中的函數 super().show() print("子類~~~show") d = Dog("fah") d.show() t = Tiger("abc") t.show(3) #函數名就是一個變量名,重寫函數的過程其實就是變量的指向發聲改變的過程 #不管子類中的函數有沒有參數,和父類的參數列表相不相同,不影響重寫,只看函數名 #t.show()
