Why do we use __init__ in Python classes? - Stack Overflow
文章推薦指數: 80 %
The __init__ function is called a constructor, or initializer, and is automatically called when you create a new instance of a class.
Lessthan10daystoRSVP!Virtuallyjoinusatourinauguralconference,everyoneiswelcome.
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
LearnmoreaboutCollectives
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
LearnmoreaboutTeams
Whydoweuse__init__inPythonclasses?
AskQuestion
Asked
10years,9monthsago
Modified
1year,3monthsago
Viewed
188ktimes
139
167
IamhavingtroubleunderstandingtheInitializationofclasses.
What'sthepointofthemandhowdoweknowwhattoincludeinthem?Doeswritinginclassesrequireadifferenttypeofthinkingversuscreatingfunctions(IfiguredIcouldjustcreatefunctionsandthenjustwraptheminaclasssoIcanre-usethem.Willthatwork?)
Here'sanexample:
classcrawler:
#Initializethecrawlerwiththenameofdatabase
def__init__(self,dbname):
self.con=sqlite.connect(dbname)
def__del__(self):
self.con.close()
defdbcommit(self):
self.con.commit()
Oranothercodesample:
classbicluster:
def__init__(self,vec,left=None,right=None,distance=0.0,id=None):
self.left=left
self.right=right
self.vec=vec
self.id=id
self.distance=distance
Therearesomanyclasseswith__init__Icomeacrosswhentryingtoreadotherpeople'scode,butIdon'tunderstandthelogicincreatingthem.
pythonclass
Share
Improvethisquestion
Follow
editedOct26,2017at17:51
Stevoisiak
21.1k2424goldbadges117117silverbadges206206bronzebadges
askedDec22,2011at20:06
LostsoulLostsoul
23.8k4343goldbadges134134silverbadges223223bronzebadges
1
1
thestoryofinitis...blah,blah,blah....constructor-destructorbutnodestructorbecausegarbagecollectionavailable.
– MisterGeeky
Jul10,2018at21:22
Addacomment
|
8Answers
8
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
316
Bywhatyouwrote,youaremissingacriticalpieceofunderstanding:thedifferencebetweenaclassandanobject.__init__doesn'tinitializeaclass,itinitializesaninstanceofaclassoranobject.Eachdoghascolour,butdogsasaclassdon't.Eachdoghasfourorfewerfeet,buttheclassofdogsdoesn't.Theclassisaconceptofanobject.WhenyouseeFidoandSpot,yourecognisetheirsimilarity,theirdoghood.That'stheclass.
Whenyousay
classDog:
def__init__(self,legs,colour):
self.legs=legs
self.colour=colour
fido=Dog(4,"brown")
spot=Dog(3,"mostlyyellow")
You'resaying,Fidoisabrowndogwith4legswhileSpotisabitofacrippleandismostlyyellow.The__init__functioniscalledaconstructor,orinitializer,andisautomaticallycalledwhenyoucreateanewinstanceofaclass.Withinthatfunction,thenewlycreatedobjectisassignedtotheparameterself.Thenotationself.legsisanattributecalledlegsoftheobjectinthevariableself.Attributesarekindoflikevariables,buttheydescribethestateofanobject,orparticularactions(functions)availabletotheobject.
However,noticethatyoudon'tsetcolourforthedoghooditself-it'sanabstractconcept.Thereareattributesthatmakesenseonclasses.Forinstance,population_sizeisonesuch-itdoesn'tmakesensetocounttheFidobecauseFidoisalwaysone.Itdoesmakesensetocountdogs.Letussaythere're200milliondogsintheworld.It'sthepropertyoftheDogclass.Fidohasnothingtodowiththenumber200million,nordoesSpot.It'scalleda"classattribute",asopposedto"instanceattributes"thatarecolourorlegsabove.
Now,tosomethinglesscanineandmoreprogramming-related.AsIwritebelow,classtoaddthingsisnotsensible-whatisitaclassof?ClassesinPythonmakeupofcollectionsofdifferentdata,thatbehavesimilarly.ClassofdogsconsistsofFidoandSpotand199999999998otheranimalssimilartothem,allofthempeeingonlampposts.Whatdoestheclassforaddingthingsconsistof?Bywhatdatainherenttothemdotheydiffer?Andwhatactionsdotheyshare?
However,numbers...thosearemoreinterestingsubjects.Say,Integers.There'salotofthem,alotmorethandogs.IknowthatPythonalreadyhasintegers,butlet'splaydumband"implement"themagain(bycheatingandusingPython'sintegers).
So,Integersareaclass.Theyhavesomedata(value),andsomebehaviours("addmetothisothernumber").Let'sshowthis:
classMyInteger:
def__init__(self,newvalue):
#imagineselfasanindexcard.
#undertheheadingof"value",wewillwrite
#thecontentsofthevariablenewvalue.
self.value=newvalue
defadd(self,other):
#whenanintegerwantstoadditselftoanotherinteger,
#we'lltaketheirvaluesandaddthemtogether,
#thenmakeanewintegerwiththeresultvalue.
returnMyInteger(self.value+other.value)
three=MyInteger(3)
#threenowcontainsanobjectofclassMyInteger
#three.valueisnow3
five=MyInteger(5)
#fivenowcontainsanobjectofclassMyInteger
#five.valueisnow5
eight=three.add(five)
#here,weinvokedthethree'sbehaviourofaddinganotherinteger
#now,eight.valueisthree.value+five.value=3+5=8
printeight.value
#==>8
Thisisabitfragile(we'reassumingotherwillbeaMyInteger),butwe'llignorenow.Inrealcode,wewouldn't;we'dtestittomakesure,andmaybeevencoerceit("you'renotaninteger?bygolly,youhave10nanosecondstobecomeone!9...8....")
Wecouldevendefinefractions.Fractionsalsoknowhowtoaddthemselves.
classMyFraction:
def__init__(self,newnumerator,newdenominator):
self.numerator=newnumerator
self.denominator=newdenominator
#becauseeveryfractionisdescribedbythesetwothings
defadd(self,other):
newdenominator=self.denominator*other.denominator
newnumerator=self.numerator*other.denominator+self.denominator*other.numerator
returnMyFraction(newnumerator,newdenominator)
There'sevenmorefractionsthanintegers(notreally,butcomputersdon'tknowthat).Let'smaketwo:
half=MyFraction(1,2)
third=MyFraction(1,3)
five_sixths=half.add(third)
printfive_sixths.numerator
#==>5
printfive_sixths.denominator
#==>6
You'renotactuallydeclaringanythinghere.Attributesarelikeanewkindofvariable.Normalvariablesonlyhaveonevalue.Letussayyouwritecolour="grey".Youcan'thaveanothervariablenamedcolourthatis"fuchsia"-notinthesameplaceinthecode.
Arrayssolvethattoadegree.Ifyousaycolour=["grey","fuchsia"],youhavestackedtwocoloursintothevariable,butyoudistinguishthembytheirposition(0,or1,inthiscase).
Attributesarevariablesthatareboundtoanobject.Likewitharrays,wecanhaveplentycolourvariables,ondifferentdogs.So,fido.colourisonevariable,butspot.colourisanother.Thefirstoneisboundtotheobjectwithinthevariablefido;thesecond,spot.Now,whenyoucallDog(4,"brown"),orthree.add(five),therewillalwaysbeaninvisibleparameter,whichwillbeassignedtothedanglingextraoneatthefrontoftheparameterlist.Itisconventionallycalledself,andwillgetthevalueoftheobjectinfrontofthedot.Thus,withintheDog's__init__(constructor),selfwillbewhateverthenewDogwillturnouttobe;withinMyInteger'sadd,selfwillbeboundtotheobjectinthevariablethree.Thus,three.valuewillbethesamevariableoutsidetheadd,asself.valuewithintheadd.
IfIsaythe_mangy_one=fido,Iwillstartreferringtotheobjectknownasfidowithyetanothername.Fromnowon,fido.colourisexactlythesamevariableasthe_mangy_one.colour.
So,thethingsinsidethe__init__.YoucanthinkofthemasnotingthingsintotheDog'sbirthcertificate.colourbyitselfisarandomvariable,couldcontainanything.fido.colourorself.colourislikeaformfieldontheDog'sidentitysheet;and__init__istheclerkfillingitoutforthefirsttime.
Anyclearer?
EDIT:Expandingonthecommentbelow:
Youmeanalistofobjects,don'tyou?
Firstofall,fidoisactuallynotanobject.Itisavariable,whichiscurrentlycontaininganobject,justlikewhenyousayx=5,xisavariablecurrentlycontainingthenumberfive.Ifyoulaterchangeyourmind,youcandofido=Cat(4,"pleasing")(aslongasyou'vecreatedaclassCat),andfidowouldfromthenon"contain"acatobject.Ifyoudofido=x,itwillthencontainthenumberfive,andnotananimalobjectatall.
Aclassbyitselfdoesn'tknowitsinstancesunlessyouspecificallywritecodetokeeptrackofthem.Forinstance:
classCat:
census=[]#definecensusarray
def__init__(self,legs,colour):
self.colour=colour
self.legs=legs
Cat.census.append(self)
Here,censusisaclass-levelattributeofCatclass.
fluffy=Cat(4,"white")
spark=Cat(4,"fiery")
Cat.census
#==>[<__main__.catinstanceat0x108982cb0>,<__main__.catinstanceat0x108982e18>]
#orsomethinglikethat
Notethatyouwon'tget[fluffy,sparky].Thosearejustvariablenames.Ifyouwantcatsthemselvestohavenames,youhavetomakeaseparateattributeforthename,andthenoverridethe__str__methodtoreturnthisname.Thismethod's(i.e.class-boundfunction,justlikeaddor__init__)purposeistodescribehowtoconverttheobjecttoastring,likewhenyouprintitout.
Share
Improvethisanswer
Follow
editedJun19,2021at11:46
mkrieger1
15.7k44goldbadges4545silverbadges5757bronzebadges
answeredDec22,2011at20:15
AmadanAmadan
183k2222goldbadges223223silverbadges282282bronzebadges
3
7
wowthanks..thisactuallymadealotofsensetomesoanythingthatmakessomethingwhatitis,Ineedtopre-declareintheinitfunction.Inthiscase,Dog,haslegsandcolour.Forexample,ifImadeaclassthataddedtwonumbers,Iwoulddeclareself.firstnumberandself.secondnumberthenjustdofirstnumber+secondnumberlateronintheclasstogettheanswer?
– Lostsoul
Dec22,2011at20:23
1
Kindof.Youcoulddothat.Butithardlymakessensetomakeaclassjusttoaddthings.Classesnormallyimplementdatawithbehaviours-purebehavioursarejustfunctions.I'llexpandtheanswerwithsomethingrelevant;waitabit.
– Amadan
Dec22,2011at20:28
3
Thankyoufortheamazinganswer.Iseeandunderstandthepowerofclassesnow.Sorry,ifitsoundsdumb.YoujustmerealizeIcansortdataandmaintainthestateofmanydifferentthingsatonce(whereasIwouldonlytrackasmanyvariablesasIcancreateormorevialoops).Sosay,Ineedtofigureouttheaveragenumberoflegsperdog?IsthereawaytoretrievealistofallobjectsIhavecreatedwithaclasssoIcanstartacalucationlikethis?orshouldIalsobemaintainingalistoftheclassesIcreate(i.e.[fido,spot])
– Lostsoul
Dec23,2011at5:33
Addacomment
|
28
Tocontributemy5centstothethoroughexplanationfromAmadan.
Whereclassesareadescription"ofatype"inanabstractway.Objectsaretheirrealizations:thelivingbreathingthing.Intheobject-orientatedworldthereareprincipalideasyoucanalmostcalltheessenceofeverything.Theyare:
encapsulation(won'telaborateonthis)
inheritance
polymorphism
Objectshaveone,ormorecharacteristics(=Attributes)andbehaviors(=Methods).Thebehaviormostlydependsonthecharacteristics.
Classesdefinewhatthebehaviorshouldaccomplishinageneralway,butaslongastheclassisnotrealized(instantiated)asanobjectitremainsanabstractconceptofapossibility.
Letmeillustratewiththehelpof"inheritance"and"polymorphism".
classHuman:
gender
nationality
favorite_drink
core_characteristic
favorite_beverage
name
age
deflove
defdrink
deflaugh
defdo_your_special_thing
classAmericans(Humans)
defdrink(beverage):
ifbeverage!=favorite_drink:print"Youcallthatadrink?"
else:print"Great!"
classFrench(Humans)
defdrink(beverage,cheese):
ifbeverage==favourite_drinkandcheese==None:print"Nocheese?"
elifbeverage!=favourite_drinkandcheese==None:print"Révolution!"
classBrazilian(Humans)
defdo_your_special_thing
win_every_football_world_cup()
classGermans(Humans)
defdrink(beverage):
iffavorite_drink!=beverage:print"Ineedmorebeer"
else:print"Lecker!"
classHighSchoolStudent(Americans):
def__init__(self,name,age):
self.name=name
self.age=age
jeff=HighSchoolStudent(name,age):
hans=Germans()
ronaldo=Brazilian()
amelie=French()
forfriendsin[jeff,hans,ronaldo]:
friends.laugh()
friends.drink("cola")
friends.do_your_special_thing()
printamelie.love(jeff)
>>>True
printronaldo.love(hans)
>>>False
Somecharacteristicsdefinehumanbeings.Buteverynationalitydifferssomewhat.So"national-types"arekindaHumanswithextras."Americans"areatypeof"Humans"andinheritsomeabstractcharacteristicsandbehaviorfromthehumantype(base-class):that'sinheritance.SoallHumanscanlaughanddrink,thereforeallchild-classescanalso!Inheritance(2).
Butbecausetheyareallofthesamekind(Type/base-class:Humans)youcanexchangethemsometimes:seethefor-loopattheend.Buttheywillexposeanindividualcharacteristic,andthatsPolymorphism(3).
Soeachhumanhasafavorite_drink,buteverynationalitytendtowardsaspecialkindofdrink.
IfyousubclassanationalityfromthetypeofHumansyoucanoverwritetheinheritedbehaviorasIhavedemonstratedabovewiththedrink()Method.
Butthat'sstillattheclass-levelandbecauseofthisit'sstillageneralization.
hans=German(favorite_drink="Cola")
instantiatestheclassGermanandI"changed"adefaultcharacteristicatthebeginning.
(Butifyoucallhans.drink('Milk')hewouldstillprint"Ineedmorebeer"-anobviousbug...ormaybethat'swhatiwouldcallafeatureifiwouldbeaEmployeeofabiggerCompany.;-)!)
Thecharacteristicofatypee.g.Germans(hans)areusuallydefinedthroughtheconstructor(inpython:__init__)atthemomentoftheinstantiation.Thisisthepointwhereyoudefineaclasstobecomeanobject.Youcouldsaybreathlifeintoanabstractconcept(class)byfillingitwithindividualcharacteristicsandbecominganobject.
Butbecauseeveryobjectisaninstanceofaclasstheyshareallsomebasiccharacteristic-typesandsomebehavior.Thisisamajoradvantageoftheobject-orientatedconcept.
Toprotectthecharacteristicsofeachobjectyouencapsulatethem-meansyoutrytocouplebehaviorandcharacteristicandmakeithardtomanipulateitfromoutsidetheobject.That'sEncapsulation(1)
Share
Improvethisanswer
Follow
editedAug29,2018at9:58
U12-Forward
66.1k1313goldbadges7676silverbadges9696bronzebadges
answeredDec22,2011at21:03
DonQuestionDonQuestion
10.9k55goldbadges3333silverbadges5151bronzebadges
Addacomment
|
6
Itisjusttoinitializetheinstance'svariables.
E.g.createacrawlerinstancewithaspecificdatabasename(fromyourexampleabove).
Share
Improvethisanswer
Follow
answeredDec22,2011at20:08
jldupontjldupont
89.5k5656goldbadges195195silverbadges310310bronzebadges
4
I'msorry,Idon'treallyunderstandwhatthatmeans..intheexampleabove..couldn'tthedeveloperjusthaveaddedinhismaincode'left=foo',etc..
– Lostsoul
Dec22,2011at20:10
Youmeanthedefaultvaluesofthefunction?left=NoneleftwillinitializedtoNoneifuponcreationtheleftparameterisn'tspecified.
– jldupont
Dec22,2011at20:13
Ithinkitsstartingtomakesense..isitlikehowyouhavetopredeclareyourvariablesinjava"Stringleft"orsomething?thenonceitsinitializedtotheclass,youcanmanipulatethevalues?ItsjustabitconfusingwhencomparedtofunctionsbecauseIcanjustsendvaluestofunctionsanddon'tneedtoinitializeanythinginadvance.
– Lostsoul
Dec22,2011at20:19
1
@Lostsoul:left=foowouldwork-once.Thepointofclassesistodosomethingsensibleforeverydifferentcrawler.Classesarenotfunctions,norsomethingthatcancomparetofunctions(well,notuntilyou'realotmoreadvancedandgetintofunctionalprogramming,butthat'lljustconfuseyounow).Readmyanswerforwhatclassesactuallyare-you'restillnotgettingit.
– Amadan
Dec22,2011at20:22
Addacomment
|
5
Followingwithyourcarexample:whenyougetacar,youjustdon'tgetarandomcar,Imean,youchoosethecolor,thebrand,numberofseats,etc.Andsomestuffisalso"initialize"withoutyouchoosingforit,likenumberofwheelsorregistrationnumber.
classCar:
def__init__(self,color,brand,number_of_seats):
self.color=color
self.brand=brand
self.number_of_seats=number_of_seats
self.number_of_wheels=4
self.registration_number=GenerateRegistrationNumber()
So,inthe__init__methodyoudefiningtheattributesoftheinstanceyou'recreating.So,ifwewantablueRenaultcar,for2people,wewouldinitializeorinstanceofCarlike:
my_car=Car('blue','Renault',2)
Thisway,wearecreatinganinstanceoftheCarclass.The__init__istheonethatishandlingourspecificattributes(likecolororbrand)anditsgeneratingtheotherattributes,likeregistration_number.
MoreaboutclassesinPython
Moreaboutthe__init__method
Share
Improvethisanswer
Follow
editedDec22,2011at20:33
answeredDec22,2011at20:14
juliomalegriajuliomalegria
23.4k1313goldbadges6868silverbadges8989bronzebadges
Addacomment
|
4
Itseemslikeyouneedtouse__init__inPythonifyouwanttocorrectlyinitializemutableattributesofyourinstances.
Seethefollowingexample:
>>>classEvilTest(object):
...attr=[]
...
>>>evil_test1=EvilTest()
>>>evil_test2=EvilTest()
>>>evil_test1.attr.append('strange')
>>>
>>>print"Thisisevil:",evil_test1.attr,evil_test2.attr
Thisisevil:['strange']['strange']
>>>
>>>
>>>classGoodTest(object):
...def__init__(self):
...self.attr=[]
...
>>>good_test1=GoodTest()
>>>good_test2=GoodTest()
>>>good_test1.attr.append('strange')
>>>
>>>print"Thisisgood:",good_test1.attr,good_test2.attr
Thisisgood:['strange'][]
ThisisquitedifferentinJavawhereeachattributeisautomaticallyinitializedwithanewvalue:
importjava.util.ArrayList;
importjava.lang.String;
classSimpleTest
{
publicArrayList
延伸文章資訊
- 1Python 入門指南- 單元11 - __init__() 方法 - 程式語言教學誌
每一種都有特定的功能,其中的__init__() 方法就是物件(object) 建立時所執行的方法,舉例如下 class Demo: def __init__(self, v1=11, v2=2...
- 2Init In Python | Python Init Class | What is Init Function - Edureka
__init__ is one of the reserved methods in Python. In object oriented programming, it is known as...
- 3Python __init__() Function - W3Schools
Create a class named Person, use the __init__() function to assign values for name and age: class...
- 4__init__ in Python: An Overview | Udacity
- 5Why do we use __init__ in Python classes? - Stack Overflow
The __init__ function is called a constructor, or initializer, and is automatically called when y...