Understanding self and __init__ method in python Class.

文章推薦指數: 80 %
投票人數:10人

"__init__" is a reseved method in python classes. It is known as a constructor in object oriented concepts. This method called when an object is ... Home Services Development PythonDevelopment DjangoDevelopment ReactDevelopment AngularDevelopment E-CommerceDevelopment DjangoRestDevelopment OscarDevelopment MobileDevelopment AndroidDevelopment ReactNativeDevelopment FlutterDevelopment UI&UXDesign Web-Responsive Bootstrap AmpDesigns Salesforce SalesforceCRM SalesforceOnboarding SalesforceDevelopment HireSalesforceDeveloper SalesforceAdmin SalesforceCustomization SalesforceIndustrySolutions SalesforceManaged SalesforceImplementation SalesforceIntegration SalesforceMarketingCloud SalesforceSalesCloud SalesforceAppexchangeDevelopment SalesforceConsulting AWSCloudServices Awsconsulting SimpleStorage SimpleNotification AwsConsultingPartner Devops Docker ServerMaintenance WebsiteMaintenanceService AboutUs FAQ's Webinars Offers OurTechStack Portfolio Blog ContactUs Book15minCall Book15minCall Wearesuccessfullycompletedanddeveloping78+Desktop&Mobileapps,Wemade32+clientshappyandmainteningSuccessfulBusinessManagement. FirstName* LookingFor* Webdevelopment Mobileappdevelopment Cloudinfrastructureplanningandmanagement Salesforceconsulting Seo CRMdevelopment Company* Website* EmailAddress* ContactNumber* SkypeID* Message* CreateSchedule Understandingselfand__init__methodinpythonClass. Beforeunderstandingthe"self"and"__init__"methodsinpythonclass,it'sveryhelpfulifwehavetheideaofwhatisaclassandobject. Class: Classisasetorcategoryofthingshavingsomepropertyorattributeincommonanddifferentiatedfromothersbykind,type,orquality. Intechnicaltermswecansaythatclassisablueprintforindividualobjectswithexactbehaviour. Object: objectisoneofinstancesoftheclass.whichcanperformthefunctionalitieswhicharedefinedintheclass. self: selfrepresentstheinstanceoftheclass.Byusingthe"self"keywordwecanaccesstheattributesandmethodsoftheclassinpython. __init__: "__init__"isaresevedmethodinpythonclasses.Itisknownasaconstructorinobjectorientedconcepts.Thismethodcalledwhenanobjectiscreatedfromtheclassanditallowtheclasstoinitializetheattributesofaclass. Howcanweuse "__init__"? Let'sconsiderthatyouarecreatingaNFSgame.forthatweshouldhaveacar.Carcanhaveattributeslike"color","company","speed_limit"etc.andmethodslike"change_gear","start","accelarate","move"etc. classCar(object): """ blueprintforcar """ def__init__(self,model,color,company,speed_limit): self.color=color self.company=company self.speed_limit=speed_limit self.model=model defstart(self): print("started") defstop(self): print("stopped") defaccelarate(self): print("accelarating...") "accelaratorfunctionalityhere" defchange_gear(self,gear_type): print("gearchanged") "gearrelatedfunctionalityhere" Letstrytocreatedifferenttypesofcars maruthi_suzuki=Car("ertiga","black","suzuki",60) audi=Car("A6","red","audi",80) Wehavecreatedtwodifferenttypesofcarobjectswiththesameclass.whilecreatingthecarobjectwepassedarguments "ertiga","black","suzuki",60 theseargumentswillpassto"__init__"method toinitializetheobject.  Here,themagickeyword"self" representstheinstanceoftheclass.Itbindstheattributeswiththegivenarguments. Usageof"self"inclasstoaccessthemethodsandattributes Case:Findoutthecostofarectangularfieldwithbreadth(b=120),length(l=160).Itcostsx(2000) rupeesper1squareunit classRectangle: def__init__(self,length,breadth,unit_cost=0):  self.length=length  self.breadth=breadth  self.unit_cost=unit_cost    defget_perimeter(self):  return2*(self.length+self.breadth)    defget_area(self):  returnself.length*self.breadth    defcalculate_cost(self):  area=self.get_area()  returnarea*self.unit_cost #breadth=120cm,length=160cm,1cm^2=Rs2000 r=Rectangle(160,120,2000) print("AreaofRectangle:%scm^2"%(r.get_area())) print("Costofrectangularfield:Rs.%s"%(r.calculate_cost())) Aswealreadydiscussed "self"representsthesameobjectorinstanceoftheclass.Ifyousee,insidethemethod"get_area" wehaveused"self.length" togetthevalueoftheattribute"length".  attribute"length"isbindtotheobject(instanceoftheclass)atthetimeofobjectcreation."self" representstheobjectinsidetheclass."self"worksjustlike"r" inthestatement "r=Rectangle(160,120,2000)". Ifyouseethemethodstructure"defget_area(self):" wehaveused"self" asaparameterinthemethodbecausewheneverwecallthemethod theobject(instanceofclass)automaticallypassesasafirstargumentalongwithotherargumetsofthemethod.Ifnootherargumentsareprovidedonly"self"ispassedtothemethod.That'sthereasonweuse"self"tocallthemethodinsidetheclass("self.get_area()"). weuseobject(instanceofclass)tocallthemethodoutsideoftheclassdefinition("r.get_area()")."r" istheinstanceoftheclass,whenwecallmethod "r.get_area()"  theinstance"r" ispassedasasfirstargumentintheplaceofself.   r=Rectangle(160,120,2000) Note:"r"istherepresentationoftheobjectoutsideoftheclassand"self"  istherepresentationoftheobjectinside theclass. formoredetailspleasevisitpythondocumentation ToKnowmoreaboutourDjangoCRM(CustomerRelationshipManagement)OpenSourcePackage.CheckCode PostedOn05May2017ByMicroPyramid Previouspost Nextpost AboutMicropyramid Micropyramidisasoftwaredevelopmentandcloudconsultingpartnerforenterprisebusinessesacrosstheworld.Weworkonpython,Django,Salesforce,Angular,Reactjs,ReactNative,MySQL,PostgreSQL,Docker,Linux,Ansible,git,amazonwebservices.WeareAmazonandsalesforceconsultingpartnerwith5yearsofcloudarchitectexperience.Wedevelope-commerce,retail,banking,machinelearning,CMS,CRMwebandmobileapplications. NeedanyHelpinyourProject?Let'sTalk down ChooseACategory Django Salesforce Python ServerManagement AmazonWebServices Javascript Mongodb ReactNative WebDevelopment Angular ProjectManagement Reactjs DjangoRestFramework Docker QualityAssurance Android SearchEngineOptimisation Ngo-Cms OurServices DjangoDevelopment PythonDevelopment ReactJSDevelopment AngularJSDevelopment DjangoEcommerceDevelopment DjangoRestFramework WebsiteMaintenanceServices OpenSourcePackages Django-CRM:CustomerrelationshipmanagementbasedonDjango Django-blog-it:djangoblogwithcompletecustomizationandreadytousewithoneclickinstallerEdit Django-webpacker:Adjangocompressortool Django-MFA:MultiFactorAuthentication Docker-box:WebInterfacetomanagefullblowndockercontainersandimages More... RelatedArticles WhatisPythonDocker?KnowNewWaystoUsePythonwithDocker WhyChoosePythonAsBackendDevelopment? WhichisthebestPythonframeworkforwebdevelopment? Python,Djangotopframeworksandit'scomparison Unittestingwithselenium-python Categories Django(97) Salesforce(63) Python(40) ServerManagement(36) AmazonWebServices(20) Javascript(12) MongoDB(8) ReactNative(5) WebDevelopment(5) Angular(4) ProjectManagement(4) ReactJS(3) DjangoRESTframework(3) Docker(2) QualityAssurance(2) Android(2) SearchEngineOptimisation(1) ngo-cms(1) SubscribeToournewsletter SubscribeandStayUpdatedaboutourWebinars,newsandarticlesonDjango,Python,MachineLearning,AmazonWebServices,DevOps,Salesforce,ReactJS,AngularJS,ReactNative. *Wedon'tprovideyouremailcontactdetailstoanythirdparties Subscribe! NeedHelp? × NeedanyHelpinyourProject?TalktoourExpertsregardingyourQueriesLet'sTalk



請為這篇文章評分?