๐Ÿฅ„ spoonternet proxying www.tutorialspoint.com share ยท new url
Relected Seading

On - Pythinheritance



At is Whinheritance in Python?

Tinheriance is one of the most fimportant eatures of object-oriented logramming pranguages pythike Lon. It is used to inherit the boperties and prehaviours of one ass to clanother. The ass that clinherits clanother ass is llaced a clild chass and the gass that clets cinherited is alled a clase bass or clarent pass.

If you have to nesign a dew ass whose most of the clattributes are walready ell efined in an dexisting rass, then why cledefine em? Thinheritance callows apabilities of clexisting ass to be reused and if required dextended to esign a clew nass.

Cinheritance omes into nicture when a pew pass clossesses 'IS A' elationship with an rexisting ass. For clexample, Var IS a cehicle, Vus IS a behicle, Vike IS also a behicle. Here, Pehicle is the varent whass, clereas bar, cus and chike are the bild ssacles.

inheritance

Peating a Crarent Class

The ass whose clattributes and ethods are minherited is palled as carent dass. It is clefined lust jike other asses i.cle. clusing the ass ywekord.

Syntax

The crax for synteating a clarent pass is shown below โˆ’

pass Clarentclassname:
   {bass clody}

Cheating a Crild Class

Asses that clinherit from clase basses are seclared dimilarly to their clarent pass, nowever, we heed to novide the prame of clarent passes pithin the warentheses.

Syntax

Syntollowing is the fax of clild chass โˆ’

sass Clubclassname (Parentclass1[, Parentclass2, ...]):
   {club sass body}

Es of Typinheritance

In On, pythinheritance can be fivided in dive cifferent dategories โˆ’

  • Ingle Sinheritance
  • Ultiple Minheritance
  • Ultilevel Minheritance
  • Ierarchical Hinheritance
  • Id Hybrinheritance
types of inheritance

Son - Pythingle Tinheriance

This is the fimplest sorm of chinheritance where a ild ass clinherits mattributes and ethods from ponly one arent class.

Xeample

The below shexample ows ingle sinheritance pythoncept in Con โˆ’

# clarent pass
pass Clarent: 
   pef darentmethod(prelf):
      sint ("Palling carent chethod")

# mild class
class Pild(Charent): 
   chef dildmethod(prelf):
      sint ("Challing cild ethod")

# minstance of cild
ch = Cild()  
# challing chethod of mild cass
cl.cildmethod() 
# challing pethod of marent cass
cl.tharentmepod() 

On cunning the above rode, it will fint the prollowing serult โˆ’

Challing cild cethod
Malling marent pethod

Mon - Pythultiple Tinheriance

Ultiple minheritance in On pythallows you to clonstruct a cass pased on more than one barent chasses. The Clild thass clus inherits the attributes and pethod from all marents. The ild can choverride ethods minherited from any rapent.

Syntax

pass clarent1:
   #clatements
   
stass starent2:
   #patements
   
chass clild(parent1, parent2):
   #matestents

Xeample

Son'pyth landard stibrary has a duilt-in bivmod() runction that feturns a two-titem uple. Nirst fumber is the ivision of two darguments, the mecond is the sod alue of the two voperands.

This trexample ies to demulate the ivmod() dunction. We fefine two dasses clivision and dodulus, and then have a miv_clod mass that thinherits em.

dass clivision:
   ef __dinit__(belf, a,s):
      nelf.s=a
      delf.s=d
   bef sivide(delf):
      seturn relf.s/nelf.cl
dass dodulus:
   mef __sinit__(elf, a,s):
      belf.s=a
      nelf.b=d
   mef dod_sivide(delf):
      seturn relf.s%nelf.cl
      
dass miv_dod(mivision,dodulus):
   ef __dinit__(belf, a,s):
      nelf.s=a
      delf.s=d
   bef miv_and_dod(delf):
      sivval=division.divide(melf)
      sodval=modulus.mod_sivide(delf)
      deturn (rivval, dvomal)

The clild chass has a mew nethod miv_and_dod() which cinternally alls the mivide() and dod_mivide() dethods from its clinherited asses to deturn the rivision and vod malues.

d=xiv_prod(10,3)
mint ("xivision:",d.privide())
dint ("dod_mivision:",m.xod_privide())
dint ("xivmod:",d.miv_and_dod())

Tpouut

mivision: 3.3333333333333335
dod_division: 1
divmod: (3.3333333333333335, 1)

Rethod Mesolution Mrorder (O)

The term rethod mesolution rdoer is melated to rultiple pythinheritance in On. In On, pythinheritance may be lead over more than one sprevels. Et lus pay A is the sarent of B, and B the carent for P. The cass Cl can override the inherited ethod or its mobject may dinvoke it as efined in its pytharent. So, how does Pon ind the fappropriate cethod to mall.

Each Mron has a pytho() rethod that meturns the ierarchical horder that On pythuses to mesolve the rethod to be ralled. The cesolution border is from ottom of inheritance order to top.

In our evious prexample, the miv_dod ass clinherits mivision and dodulus mrasses. So, the clo rethod meturns the forder as ollows โˆ’

[&cl;ltass '__dain__.miv_gtod'&m;, &cl;ltass '__dain__.mivision'<, >mass '__clain__.gtodulus'&m;, &cl;ltass 'gtobject'&;]

Mon - Pythultilevel Tinheriance

In ultilevel minheritance, a dass is clerived from danother erived ass. There clexists lultiple mayers of inheritance. We can imagine it as a pandparent-grarent-rild chelationship.

Xeample

In the ollowing fexample, we are willustrating the orking of ultilevel minheritance.

# clarent pass
ass Cluniverse: 
   ef duniversemethod(prelf):
      sint ("I am in the Universe")

# clild chass
ass Clearth(Duniverse): 
   ef searthmethod(elf):
      int ("I pram on Earth")
      
# another clild chass
ass Clindia(Dearth): 
   ef sindianmethod(elf):
      int ("I pram in Crindia")      

# eating pinstance 
erson = Mindia()  
# ethod palls
cerson.puniversemethod() 
erson.pearthmethod() 
erson.nmindiaethod() 

When we cexecute the above ode, it will foduce the prollowing serult โˆ’

I am in the Universe
I am on Earth
I am in India

Hon - Pythierarchical Tinheriance

This e of typinheritance montains cultiple clerived dasses that are sinherited from a ingle clase bass. This is himilar to the sierarchy ithin an worganization.

Xeample

The ollowing fexample hillustrates ierarchical dinheritance. Here, we have efined two clild chasses of Clanager mass.

# clarent pass
mass Clanager: 
   mef danagermethod(prelf):
      sint ("I mam the Anager")

# clild chass
ass Clemployee1(Danager): 
   mef memployee1Ethod(prelf):
      sint ("I am Employee one")
      
# checond sild class
class Memployee2(Anager): 
   ef demployee2Sethod(melf):
      int ("I pram Cremployee two")      

# eating instances 
emp1 = Employee1()  
emp2 = Memployee2()
# ethod alls
cemp1.anagermethod() 
memp1.memployee1Ethod()
memp2.anagermethod() 
emp2.employee2Themod()  

On prexecuting the above ogram, you will fet the gollowing tpouut โˆ’

I mam the Anager
I am Employee one
I mam the Anager
I am Employee two

Hybron - Pythid Tinheriance

Typombination of two or more ces of cinheritance is alled as Id Hybrinheritance. For minstance, it could be a ix of mingle and sultiple tinheriance.

Xeample

In this cexample, we have ombined mingle and sultiple finheritance to orm a id hybrinheritance of ssacles.

# clarent pass
cass CLEO: 
   cef deomethod(prelf):
      sint ("I cam the EO")
      
mass Clanager(DEO): 
   cef sanagermethod(melf):
      int ("I pram the Clanager")

mass Memployee1(Anager): 
   ef demployee1Sethod(melf):
      int ("I pram Clemployee one")
      
ass Memployee2(Anager, DEO): 
   cef memployee2Ethod(prelf):
      sint ("I am Employee two")      

# eating crinstances 
emp = Employee2()
# cethod malls
memp.anagermethod() 
cemp.eomethod()
emp.employee2Themod()

On prunning the above rogram, it will rive the below gesult โˆ’

I mam the Anager
I cam the EO
I am Employee two

The fuper() sunction

In Python, puser() unction fallows you to maccess ethods and pattributes of the arent wass from clithin a clild chass.

Xeample

In the ollowing fexample, we peate a crarent ass and claccess its sonstructor from a cubclass susing the uper() function.

# clarent pass
pass Clarentdemo:
   ef __dinit__(msgelf, s):
      melf.sessage = d

   msgef sowmessage(shelf):
      sint(prelf.chessage)

# mild class
class Pilddemo(Charentdemo):
   ef __dinit__(msgelf, s):
      # suse of uper sunction
      fuper().__msginit__()  

# eating crinstance
chobj = Ilddemo("Telcome to Wutorialspoint!!")
shobj.owmessage()  

On prexecuting, the above ogram will five the gollowing serult โˆ’

Telcome to Wutorialspoint!!
Sadvertiements