Introduction to classes and type in Python - Educative.io

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

If you look for type in the Python help console, you will see a description of the arguments that type takes in order to create a class. It is worth noting that ... SolutionsEducativeEnterpriseEnablementplatformDevelopersLearnnewtechnologiesProductsCoursesforEnterpriseSuperchargeyourengineeringteamCoursesforIndividualsWorldclasscoursesOnboardingOnboardnewhiresfasterAssessmentsMeasureyourSkillScorePersonalizedLearningPlansPersonalizedPlansforyourgoalsProjectsBuildrealworldapplicationsAnswersTrustedAnswerstoDeveloperQuestionsPricingForEnterpriseTailoredforyourteamForIndividualsStayaheadofthecurveCoursesLogInJoin forfreeTrustedanswerstodeveloperquestionsTrustedAnswerstoDeveloperQuestionsRelatedTagspython3pythonoopcommunitycreatorIntroductiontoclassesandtypeinPythonJosiasAurelGrokkingModernSystemDesignInterviewforEngineers&ManagersAceyourSystemDesignInterviewandtakeyourcareertothenextlevel.LearntohandlethedesignofapplicationslikeNetflix,Quora,Facebook,Uber,andmanymoreina45-mininterview.LearntheRESHADEDframeworkforarchitectingweb-scaleapplicationsbydeterminingrequirements,constraints,andassumptionsbeforedivingintoastep-by-stepdesignprocess. StartLearningInthispost,wearegoingtodiscussPythonclassesandtype. SincePythonisanobject-orientedlanguage,everythingisanobjectandadescendantofaclass. But,whatyoumightnotknow,isthateveryclassisitselfdescendantofanotherclassknownastype. InPython,wehavethebuilt-intype()functionthatletsyouviewthetypeofanyobjectinPython. Takealookattheexamplebelow: name="Mike" print(type(name))RunWeseethatthetypeofnameisastring. Now,let’strybuildingourownclass. WearegoingtobuildaclasscalledFruitandinstantiatedescendantfruitsfromourFruitclass. classFruit: def__init__(self,color,shape): self.color=color self.shape=shape defshow_characteristics(self): characteristics=[self.shape,self.color] returncharacteristicsRunWeknowthatwecaninstantiateafruitfromourFruitclassandwewillhavedescendant. Earlier,wementionedthatevenclassesaredescendantofanotherclassabovethem.Thismeansthatstrings,integers,andourFruitclasshasahigherclassaboveit. Thetypeclass WhenyouinspectthetypeofanobjectlikeaninstanceofourFruit,orastringobjectlikeournameusingthetype()function,itwillreturntheparentofthatobjecttoyou. ButwhatwillhappenifwetrytogetthetypeofourFruitclassitself? classFruit: def__init__(self,color,shape): self.color=color self.shape=shape defshow_characteristics(self): characteristics=[self.shape,self.color] returncharacteristics print(type(Fruit))RunYouwillgetasanoutput.Ifyoutrytoexecuteitonstr,int,type,orotherPythonclasses,youwillget. Thisisbecauseallclassesandobjectsinheritfromthetypeclassaboveeverythingelse.Therefore,itispossibletore-createourfruitclassdirectlyfromtype. Creatingaclasswithtype IfyoulookfortypeinthePythonhelpconsole,youwillseeadescriptionoftheargumentsthattypetakesinordertocreateaclass. Itisworthnotingthattypetakeseither1or3arguments.Whenasingleargumentispassed,itwillreturntheclassfromwhichtheobjectinherits.When3argumentsarepassed,itreturnsnewclasstoyouwiththecharacteristicsandattributesyoupassedinaslastargument.Moreonthisbelow. Thefirstargumentittakesisthenameoftheclassyouarecreating. Thesecondargumentisthebasesfromwhichyourclasswouldinherit.Sayyouarecreatinganewclassthatinheritsfromstr,thenyouwouldpassatupleasthesecondargument. Thethirdargumentisadictionarythatwillholdthemethodsandvariablesinsideourclass. Now,let’screateourclass.WearegoingtorecreatethesameFruitclassasabove. deffruit_init(self,shape,color): self.shape=shape self.color=color defshow_characteristics(self): characteristics=[self.color,self.shape] returncharacteristics fruit_class=type("FruitClass",(),{"__init__":fruit_init,"show_characteristics":show_characteristics})RunLet’sexplorewhatishappeninghere. WearecreatingaclasscalledFruitClass,whichinheritsfromnootherclass(thustheemptytuple). Ourclasshassomemethodslikeinitandshow_characteristics,whichmaptothefunctionswecreatedabove. Wecreatedthosefunctionsabovebecauseitwillbehardtofitthemintothedictionary,butyoucouldmakeuseoflambdaexpressionsthere. Whatweendupwithisaclassthatwecanuse.Let’stryitout. deffruit_init(self,shape,color): self.shape=shape self.color=color defshow_characteristics(self): characteristics=[self.color,self.shape] returncharacteristics fruit_class=type("FruitClass",(),{ "__init__":fruit_init,"show_characteristics":show_characteristics}) orange=fruit_class("spherical","orange") print(orange.show_characteristics())RunHowisthisuseful? IfyouhaveknowledgeoftheaboveunderlyingfunctioninginPython,youwillbeabletobetterunderstandthebehaviorofobjectsandsomeclassesinPython.Withthis,youcanevendefineyourownblueprintsforcreatingotherclassesandtypes,justbycreatingaclassthatinheritsfromthetypeclassabove. Thiswillgiveyouthepowertobeabletodefineyourownbehaviorforobjects,andevensetrulesonwhathappenswhenanewobjectiscreated. RELATEDTAGSpython3pythonoopcommunitycreatorCONTRIBUTORJosiasAurelLicense:CreativeCommons-Attribution-ShareAlike4.0(CC-BY-SA4.0)GrokkingModernSystemDesignInterviewforEngineers&ManagersAceyourSystemDesignInterviewandtakeyourcareertothenextlevel.LearntohandlethedesignofapplicationslikeNetflix,Quora,Facebook,Uber,andmanymoreina45-mininterview.LearntheRESHADEDframeworkforarchitectingweb-scaleapplicationsbydeterminingrequirements,constraints,andassumptionsbeforedivingintoastep-by-stepdesignprocess. StartLearningKeepExploringRelatedCoursesLearnin-demandtechskillsinhalfthetimeSOLUTIONSForEnterpriseForIndividualsForHR&RecruitingForBootcampsPRODUCTSEducativeLearningEducativeOnboardingEducativeSkillAssessmentsEducativeProjectsPricingForEnterpriseForIndividualsFreeTrialLEGALPrivacyPolicyCookieSettingsTermsofServiceBusinessTermsofServiceCONTRIBUTEBecomeanAuthorBecomeanAffiliateBecomeaContributorRESOURCESEducativeBlogEMHubEducativeSessionsEducativeAnswersABOUTUSOurTeamCareersHiringFrequentlyAskedQuestionsContactUsPressMOREGitHubStudentsScholarshipCourseCatalogEarlyAccessCoursesEarnReferralCreditsCodingInterview.comCopyright©2022Educative,Inc.Allrightsreserved.



請為這篇文章評分?