Python super()
V Pythonu se funkcija super() uporablja za sklicevanje na nadrejeni razred ali nadrazred. Omogoča vam klicanje metod, definiranih v nadrazredu, iz podrazreda, kar vam omogoča, da razširite in prilagodite funkcionalnost, podedovano iz nadrejenega razreda.
Sintaksa super() v Pythonu
Sintaksa: super()
Povratek: Vrne proxy objekt, ki predstavlja nadrejeni razred.
funkcija super() v primeru Pythona
V danem primeru The Emp razred ima __vroče__ metoda, ki inicializira id , in ime in Dodaja lastnosti. The Samostojni razred podeduje od Emp razred in doda dodaten atribut imenovan E-poštna sporočila. Pokliče metodo __init__ nadrejenega razreda super(), da inicializira podedovani atribut.
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)> |
Izhod:
The ID is: 103 The Name is: Suraj kr gupta The Address is: Noida The Emails is: KKK@gmails
Za kaj se uporablja metoda super ()?
Metodo iz nadrejenega razreda je mogoče poklicati v Pythonu s funkcijo super(). To je tipična praksa v objektno orientirano programiranje za klicanje metod nadrazreda in omogočanje preglasitve in dedovanja metod. Tudi če je trenutni razred nadomestil te metode z lastno izvedbo, vam klic super() omogoča dostop do metod nadrejenega razreda in njihovo uporabo. S tem lahko izboljšate in spremenite vedenje nadrejenega razreda, hkrati pa še vedno pridobite od tega.
Prednosti Super Function
- Za dostop do njegovih metod si ni treba zapomniti ali določiti imena nadrejenega razreda. To funkcijo je mogoče uporabiti pri enojnem in večkratnem dedovanju.
- To izvaja modularnost (izoliranje sprememb) in možnost ponovne uporabe kode, saj ni potrebe po prepisu celotne funkcije.
- Super funkcija v Pythonu se kliče dinamično, ker je Python dinamičen jezik, za razliko od drugih jezikov.
Kako deluje dedovanje brez Python super?
V danem primeru je težava z metodo __init__ razreda Emp. Razred Emp je podedovan od razreda Person, vendar v svoji metodi __init__ ne kliče metode __init__ nadrejenega razreda za inicializacijo atributov imena in 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> |
Izhod:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in 24 25 # calling parent class function --->26 Emp_details.name_, Emp_details.name AttributeError: Objekt 'Emp' nima atributa 'name'
Odpravljanje zgornje težave s Super v Pythonu
V predloženi kodi razred Emp pravilno deduje od razreda Person in metoda __init__ razreda Emp zdaj pravilno kliče metodo __init__ nadrejenega razreda z uporabo super() v Pythonu.
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)> |
Izhod:
Mayank Mayank
Razumevanje Python super() z metodami __init__().
Python ima rezervirano metodo, imenovano __init__. V objektno usmerjenem programiranju se imenuje konstruktor. Ko se ta metoda pokliče, omogoči razredu, da inicializira atribute razreda. V podedovanem podrazredu se lahko na nadrejeni razred sklicujete z uporabo funkcije super(). Super funkcija vrne začasni objekt nadrazreda, ki omogoča dostop do vseh njegovih metod njegovemu podrejenemu razredu.
Opomba: Za več informacij glejte Dedovanje v Pythonu .
Super funkcija z enojnim dedovanjem
Vzemimo primer živali. Psi, mačke in krave so del živali. Imajo tudi skupne značilnosti, kot so –
- So sesalci.
- Imajo rep in štiri noge.
- So domače živali.
Torej so razredi psi, mačke in konji podrazred razreda živali. To je primer enojnega dedovanja, ker je veliko podrazredov podedovanih od enostarševskega razreda.
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()> |
Izhod:
It is a mammal. Has legs and tail
Super z več dedovanjem
Vzemimo drugo primer super funkcije , Recimo razred lahko leti in zna plavati podedujejo od razreda sesalcev in te razrede podeduje razred živali. Torej razred živali deduje več osnovnih razredov. Poglejmo si uporabo Python super z argumenti v tem primeru.
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'> )> |
Izhod:
Razred Animal deduje od dveh starševskih razredov – canFly in canSwim. Torej lahko primerek podrazreda Carol dostopa do obeh konstruktorjev nadrejenega razreda.
Dog cannot fly Dog cannot swim Dog Is a mammal
Super z večnivojskim dedovanjem
Vzemimo drugo primer super funkcije , predpostavimo, da razred zna plavati podeduje canFly, canFly iz razreda sesalcev. Torej razred sesalcev deduje iz večnivojskega dedovanja. Poglejmo si uporabo Python super z argumenti v tem primeru.
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'> )> |
Izhod:
Dog cannot swim Dog cannot fly Dog Is a mammal
Python večkratno dedovanje in MRO
V danem primeru razred C podeduje razrede A in B ter preglasi metodo age(). Vendar pa v metodi age() razreda C vrstica super(C, self).age() prikliče metodo age() iz naslednjega razreda v MRO. V tem primeru bo priklical metodo age() iz razreda A, ker se v MRO pojavi pred razredom 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())> |
Izhod:
(, , , ) [, , , ]