Python super()

V Pythone sa funkcia super() používa na odkazovanie na nadradenú triedu alebo nadtriedu. Umožňuje vám volať metódy definované v nadtriede z podtriedy, čo vám umožňuje rozšíriť a prispôsobiť funkčnosť zdedenú z nadradenej triedy.

Syntax super() v Pythone

Syntax: Super()

Návrat : Vráti objekt proxy, ktorý predstavuje triedu rodiča.

funkcia super() v príklade Pythonu

V uvedenom príklade The Emp trieda má __horúce__ metóda, ktorá inicializuje id , a názov a Pridáva atribúty. The Na voľnej nohe trieda dedí z Emp class a pridáva ďalší atribút tzv E-maily. Zavolá metódu __init__ nadradenej triedy super() na inicializáciu zdedeného atribútu.

Python3




class> Emp():> > def> __init__(> self> ,> id> , name, Add):> > self> .> id> => id> > self> .name> => name> > self> .Add> => Add> # Class freelancer inherits EMP> class> Freelance(Emp):> > def> __init__(> self> ,> id> , name, Add, Emails):> > super> ().__init__(> id> , name, Add)> > self> .Emails> => Emails> Emp_1> => Freelance(> 103> ,> 'Suraj kr gupta'> ,> 'Noida'> ,> 'KKK@gmails'> )> print> (> 'The ID is:'> , Emp_1.> id> )> print> (> 'The Name is:'> , Emp_1.name)> print> (> 'The Address is:'> , Emp_1.Add)> print> (> 'The Emails is:'> , Emp_1.Emails)>

Výkon :

The ID is: 103 The Name is: Suraj kr gupta The Address is: Noida The Emails is: KKK@gmails 

Na čo sa používa metóda super ()?

Metódu z nadradenej triedy možno volať v Pythone pomocou funkcie super(). Je to typická prax v objektovo orientované programovanie na volanie metód nadtriedy a umožnenie prepisovania a dedenia metódy. Aj keď aktuálna trieda nahradila tieto metódy vlastnou implementáciou, volanie super() vám umožní prístup a používanie metód nadradenej triedy. Týmto spôsobom môžete vylepšiť a upraviť správanie rodičovskej triedy a zároveň z toho získať.

Výhody super funkcie

  • Na prístup k jej metódam si nemusíte pamätať alebo špecifikovať názov nadradenej triedy. Túto funkciu je možné použiť pri jednoduchej aj viacnásobnej dedičnosti.
  • To implementuje modularitu (izolovanie zmien) a opätovnú použiteľnosť kódu, pretože nie je potrebné prepisovať celú funkciu.
  • Super funkcia v Pythone sa nazýva dynamicky, pretože Python je dynamický jazyk, na rozdiel od iných jazykov.

Ako funguje dedičnosť bez super Pythonu?

V uvedenom príklade je problém s metódou __init__ triedy Emp. Trieda Emp je zdedená z triedy Person, ale vo svojej metóde __init__ nevolá metódu __init__ nadradenej triedy na inicializáciu atribútov name a id.

Python3




# code> class> Person:> > # Constructor> > def> __init__(> self> , name,> id> ):> > self> .name> => name> > self> .> id> => id> > # To check if this person is an employee> > def> Display(> self> ):> > print> (> self> .name,> self> .> id> )> > class> Emp(Person):> > > def> __init__(> self> , name,> id> ):> > self> .name_> => name> > def> Print> (> self> ):> > print> (> 'Emp class called'> )> Emp_details> => Emp(> 'Mayank'> ,> 103> )> # calling parent class function> Emp_details.name_, Emp_details.name>

Výkon :

--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in 24 25 # calling parent class function --->26 Emp_details.name_, Emp_details.name AttributeError: Objekt 'Emp' nemá atribút 'name' 

Oprava vyššie uvedeného problému so Super v Pythone

V poskytnutom kóde trieda Emp správne dedí z triedy Person a metóda __init__ triedy Emp teraz správne volá metódu __init__ nadradenej triedy pomocou super() v Pythone.

Python3




# code> # A Python program to demonstrate inheritance> class> Person:> > # Constructor> > def> __init__(> self> , name,> id> ):> > self> .name> => name> > self> .> id> => id> > # To check if this person is an employee> > def> Display(> self> ):> > print> (> self> .name,> self> .> id> )> > class> Emp(Person):> > > def> __init__(> self> , name,> id> ):> > self> .name_> => name> > super> ().__init__(name,> id> )> > def> Print> (> self> ):> > print> (> 'Emp class called'> )> Emp_details> => Emp(> 'Mayank'> ,> 103> )> # calling parent class function> print> (Emp_details.name_, Emp_details.name)>

Výkon :

Mayank Mayank 

Pochopenie super() Pythonu s metódami __init__().

Python má vyhradenú metódu s názvom __init__. V objektovo orientovanom programovaní sa označuje ako konštruktor. Keď sa volá táto metóda, umožňuje triede inicializovať atribúty triedy. V zdedenej podtriede možno odkazovať na rodičovskú triedu pomocou funkcie super(). Funkcia super vracia dočasný objekt nadtriedy, ktorý umožňuje prístup ku všetkým jej metódam do podradenej triedy.

Poznámka: Ďalšie informácie nájdete v časti Dedičnosť v Pythone .

Super funkcia s jednoduchým dedičstvom

Vezmime si príklad zvierat. Psy, mačky a kravy sú súčasťou zvierat. Majú tiež spoločné vlastnosti, ako napr.

  • Sú to cicavce.
  • Majú chvost a štyri nohy.
  • Sú to domáce zvieratá.

Takže triedy psy, mačky a kone sú podtriedou triedy zvierat. Toto je príklad jednoduchého dedenia, pretože mnoho podtried je dedených z jednej nadradenej triedy.

Python3




# Python program to demonstrate> # super function> class> Animals:> > # Initializing constructor> > def> __init__(> self> ):> > self> .legs> => 4> > self> .domestic> => True> > self> .tail> => True> > self> .mammals> => True> > def> isMammal(> self> ):> > if> self> .mammals:> > print> (> 'It is a mammal.'> )> > def> isDomestic(> self> ):> > if> self> .domestic:> > print> (> 'It is a domestic animal.'> )> class> Dogs(Animals):> > def> __init__(> self> ):> > super> ().__init__()> > def> isMammal(> self> ):> > super> ().isMammal()> class> Horses(Animals):> > def> __init__(> self> ):> > super> ().__init__()> > def> hasTailandLegs(> self> ):> > if> self> .tail> and> self> .legs> => => 4> :> > print> (> 'Has legs and tail'> )> # Driver code> Tom> => Dogs()> Tom.isMammal()> Bruno> => Horses()> Bruno.hasTailandLegs()>

Výkon :

It is a mammal. Has legs and tail 

Super s viacnásobným dedičstvom

Vezmime si ďalšie príklad super funkcie , Predstavte si triedu moct lietat a vie plávať dedí z triedy cicavcov a tieto triedy sú zdedené triedou zvierat. Takže trieda zvierat dedí z viacerých základných tried. Pozrime sa na použitie Python super s argumentmi v tomto prípade.

Python3




class> Mammal():> > def> __init__(> self> , name):> > print> (name,> 'Is a mammal'> )> class> canFly(Mammal):> > def> __init__(> self> , canFly_name):> > print> (canFly_name,> 'cannot fly'> )> > # Calling Parent class> > # Constructor> > super> ().__init__(canFly_name)> class> canSwim(Mammal):> > def> __init__(> self> , canSwim_name):> > print> (canSwim_name,> 'cannot swim'> )> > super> ().__init__(canSwim_name)> class> Animal(canFly, canSwim):> > def> __init__(> self> , name):> > super> ().__init__(name)> # Driver Code> Carol> => Animal(> 'Dog'> )>

Výkon :

Trieda Zviera sa dedí po triedach s dvoma rodičmi – canFly a canSwim. Inštancia podtriedy Carol má teda prístup k obom konštruktorom rodičovskej triedy.

Dog cannot fly Dog cannot swim Dog Is a mammal 

Super s viacúrovňovou dedičnosťou

Vezmime si ďalšie príklad super funkcie Predpokladajme, že triedu vie plávať zdedí canFly, canFly z triedy cicavcov. Takže trieda cicavcov dedí z viacúrovňovej dedičnosti. Pozrime sa na použitie Python super s argumentmi v tomto prípade.

Python3




class> Mammal():> > def> __init__(> self> , name):> > print> (name,> 'Is a mammal'> )> class> canFly(Mammal):> > def> __init__(> self> , canFly_name):> > print> (canFly_name,> 'cannot fly'> )> > # Calling Parent class> > # Constructor> > super> ().__init__(canFly_name)> class> canSwim(canFly):> > def> __init__(> self> , canSwim_name):> > print> (canSwim_name,> 'cannot swim'> )> > super> ().__init__(canSwim_name)> class> Animal(canSwim):> > def> __init__(> self> , name):> > # Calling the constructor> > # of both the parent> > # class in the order of> > # their inheritance> > super> ().__init__(name)> # Driver Code> Carol> => Animal(> 'Dog'> )>

Výkon :

Dog cannot swim Dog cannot fly Dog Is a mammal 

Viacnásobná dedičnosť Pythonu a MRO

V uvedenom príklade trieda C dedí z tried A a B a má prednosť pred metódou age(). V metóde age() triedy C však riadok super(C, self).age() vyvoláva metódu age() z ďalšej triedy v MRO. V tomto prípade vyvolá metódu age() z triedy A, pretože sa v MRO nachádza pred triedou B.

Python3




class> A:> > def> age(> self> ):> > print> (> 'Age is 21'> )> class> B:> > def> age(> self> ):> > print> (> 'Age is 23'> )> class> C(A, B):> > def> age(> self> ):> > super> (C,> self> ).age()> > c> => C()> print> (C.__mro__)> print> (C.mro())>

Výkon :

(, , , ) [, , , ]