Python OOPs Concepts - GeeksforGeeks

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

In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in programming. It aims to implement ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesPythonOOPsConceptsObjectOrientedProgramminginPython|Set2(DataHidingandObjectPrinting)OOPinPython|Set3(Inheritance,examplesofobject,issubclassandsuper)ClassmethodvsStaticmethodinPythonClassorStaticVariablesinPythonChangingClassMembersinPythonConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonAbstractClassesinPythonDefaultdictinPythonPythonmap()functionreduce()inPythonfilter()inpythonPythonLambdaFunctionsLambdaandfilterinPythonExamplesIntersectionoftwoarraysinPython(Lambdaexpressionandfilterfunction)G-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonAddingnewcolumntoexistingDataFrameinPandasReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframePythonOOPsConceptsObjectOrientedProgramminginPython|Set2(DataHidingandObjectPrinting)OOPinPython|Set3(Inheritance,examplesofobject,issubclassandsuper)ClassmethodvsStaticmethodinPythonClassorStaticVariablesinPythonChangingClassMembersinPythonConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonAbstractClassesinPythonDefaultdictinPythonPythonmap()functionreduce()inPythonfilter()inpythonPythonLambdaFunctionsLambdaandfilterinPythonExamplesIntersectionoftwoarraysinPython(Lambdaexpressionandfilterfunction)G-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonAddingnewcolumntoexistingDataFrameinPandasReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframePythonOOPsConceptsViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 14Jun,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle InPython,object-orientedProgramming(OOPs)isaprogrammingparadigmthatusesobjectsandclassesinprogramming.Itaimstoimplementreal-worldentitieslikeinheritance,polymorphisms,encapsulation,etc.intheprogramming.ThemainconceptofOOPsistobindthedataandthefunctionsthatworkonthattogetherasasingleunitsothatnootherpartofthecodecanaccessthisdata.MainConceptsofObject-OrientedProgramming(OOPs) ClassObjectsPolymorphismEncapsulationInheritanceDataAbstractionOOPs Class Aclassisacollectionofobjects.Aclasscontainstheblueprintsortheprototypefromwhichtheobjectsarebeingcreated.Itisalogicalentitythatcontainssomeattributesandmethods. Tounderstandtheneedforcreatingaclasslet’sconsideranexample,let’ssayyouwantedtotrackthenumberofdogsthatmayhavedifferentattributeslikebreed,age.Ifalistisused,thefirstelementcouldbethedog’sbreedwhilethesecondelementcouldrepresentitsage.Let’ssupposethereare100differentdogs,thenhowwouldyouknowwhichelementissupposedtobewhich?Whatifyouwantedtoaddotherpropertiestothesedogs?Thislacksorganizationandit’stheexactneedforclasses. SomepointsonPythonclass: Classesarecreatedbykeywordclass.Attributesarethevariablesthatbelongtoaclass.Attributesarealwayspublicandcanbeaccessedusingthedot(.)operator.Eg.:Myclass.MyattributeClassDefinitionSyntax:classClassName: #Statement-1 . . . #Statement-NExample:CreatinganemptyClassinPythonPython#Python3programto#demonstratedefining#aclass classDog:    passIntheaboveexample,wehavecreatedaclassnameddogusingtheclasskeyword.ObjectsTheobjectisanentitythathasastateandbehaviorassociatedwithit.Itmaybeanyreal-worldobjectlikeamouse,keyboard,chair,table,pen,etc.Integers,strings,floating-pointnumbers,evenarrays,anddictionaries,areallobjects.Morespecifically,anysingleintegeroranysinglestringisanobject.Thenumber12isanobject,thestring“Hello,world”isanobject,alistisanobjectthatcanholdotherobjects,andsoon.You’vebeenusingobjectsallalongandmaynotevenrealizeit.Anobjectconsistsof:State:Itisrepresentedbytheattributesofanobject.Italsoreflectsthepropertiesofanobject.Behavior:Itisrepresentedbythemethodsofanobject.Italsoreflectstheresponseofanobjecttootherobjects.Identity:Itgivesauniquenametoanobjectandenablesoneobjecttointeractwithotherobjects.Tounderstandthestate,behavior,andidentityletustaketheexampleoftheclassdog(explainedabove). Theidentitycanbeconsideredasthenameofthedog.StateorAttributescanbeconsideredasthebreed,age,orcolorofthedog.Thebehaviorcanbeconsideredastowhetherthedogiseatingorsleeping.Example:CreatinganobjectPython3obj=Dog()ThiswillcreateanobjectnamedobjoftheclassDogdefinedabove.Beforedivingdeepintoobjectsandclassletusunderstandsomebasickeywordsthatwillweusedwhileworkingwithobjectsandclasses.Theself  Classmethodsmusthaveanextrafirstparameterinthemethoddefinition.Wedonotgiveavalueforthisparameterwhenwecallthemethod,PythonprovidesitIfwehaveamethodthattakesnoarguments,thenwestillhavetohaveoneargument.ThisissimilartothispointerinC++andthisreferenceinJava.Whenwecallamethodofthisobjectasmyobject.method(arg1,arg2),thisisautomaticallyconvertedbyPythonintoMyClass.method(myobject,arg1,arg2)–thisisallthespecialselfisabout.Note:Formoreinformation,refertoselfinPythonclassThe__init__method The__init__methodissimilartoconstructorsinC++andJava.Itisrunassoonasanobjectofaclassisinstantiated.Themethodisusefultodoanyinitializationyouwanttodowithyourobject. Nowletusdefineaclassandcreatesomeobjectsusingtheselfand__init__method.Example1:CreatingaclassandobjectwithclassandinstanceattributesPython3classDog:     #classattribute    attr1="mammal"     #Instanceattribute    def__init__(self,name):        self.name=name #Drivercode#ObjectinstantiationRodger=Dog("Rodger")Tommy=Dog("Tommy") #Accessingclassattributesprint("Rodgerisa{}".format(Rodger.__class__.attr1))print("Tommyisalsoa{}".format(Tommy.__class__.attr1)) #Accessinginstanceattributesprint("Mynameis{}".format(Rodger.name))print("Mynameis{}".format(Tommy.name))OutputRodgerisamammal Tommyisalsoamammal MynameisRodger MynameisTommyExample2:CreatingClassandobjectswithmethodsPython3classDog:     #classattribute    attr1="mammal"     #Instanceattribute    def__init__(self,name):        self.name=name             defspeak(self):        print("Mynameis{}".format(self.name)) #Drivercode#ObjectinstantiationRodger=Dog("Rodger")Tommy=Dog("Tommy") #AccessingclassmethodsRodger.speak()Tommy.speak()OutputMynameisRodger MynameisTommyNote:Formoreinformation,referPythonClassesandObjectsInheritanceInheritanceisthecapabilityofoneclasstoderiveorinheritthepropertiesfromanotherclass.Theclassthatderivespropertiesiscalledthederivedclassorchildclassandtheclassfromwhichthepropertiesarebeingderivediscalledthebaseclassorparentclass.Thebenefitsofinheritanceare:Itrepresentsreal-worldrelationshipswell.Itprovidesthereusabilityofacode.Wedon’thavetowritethesamecodeagainandagain.Also,itallowsustoaddmorefeaturestoaclasswithoutmodifyingit.Itistransitiveinnature,whichmeansthatifclassBinheritsfromanotherclassA,thenallthesubclassesofBwouldautomaticallyinheritfromclassA.TypesofInheritance– SingleInheritance:Single-levelinheritanceenablesaderivedclasstoinheritcharacteristicsfromasingle-parentclass.MultilevelInheritance:Multi-levelinheritanceenablesaderivedclasstoinheritpropertiesfromanimmediateparentclasswhichinturninheritspropertiesfromhisparentclass.HierarchicalInheritance:Hierarchicallevelinheritanceenablesmorethanonederivedclasstoinheritpropertiesfromaparentclass.MultipleInheritance:Multiplelevelinheritanceenablesonederivedclasstoinheritpropertiesfrommorethanonebaseclass.Example:InheritanceinPythonPython3#Pythoncodetodemonstratehowparentconstructors#arecalled. #parentclassclassPerson(object):     #__init__isknownastheconstructor    def__init__(self,name,idnumber):        self.name=name        self.idnumber=idnumber     defdisplay(self):        print(self.name)        print(self.idnumber)             defdetails(self):        print("Mynameis{}".format(self.name))        print("IdNumber:{}".format(self.idnumber))     #childclassclassEmployee(Person):    def__init__(self,name,idnumber,salary,post):        self.salary=salary        self.post=post         #invokingthe__init__oftheparentclass        Person.__init__(self,name,idnumber)             defdetails(self):        print("Mynameis{}".format(self.name))        print("IdNumber:{}".format(self.idnumber))        print("Post:{}".format(self.post))  #creationofanobjectvariableoraninstancea=Employee('Rahul',886012,200000,"Intern") #callingafunctionoftheclassPersonusing#itsinstancea.display()a.details()OutputRahul 886012 MynameisRahul IdNumber:886012 Post:InternIntheabovearticle,wehavecreatedtwoclassesi.e.Person(parentclass)andEmployee(ChildClass).TheEmployeeclassinheritsfromthePersonclass.Wecanusethemethodsofthepersonclassthroughemployeeclassasseeninthedisplayfunctionintheabovecode.Achildclasscanalsomodifythebehavioroftheparentclassasseenthroughthedetails()method.Note:Formoreinformation,refertoourInheritanceinPythontutorial.PolymorphismPolymorphismsimplymeanshavingmanyforms.Forexample,weneedtodetermineifthegivenspeciesofbirdsflyornot,usingpolymorphismwecandothisusingasinglefunction.Example:PolymorphisminPythonPython3classBird:       defintro(self):        print("Therearemanytypesofbirds.")     defflight(self):        print("Mostofthebirdscanflybutsomecannot.") classsparrow(Bird):       defflight(self):        print("Sparrowscanfly.") classostrich(Bird):     defflight(self):        print("Ostrichescannotfly.") obj_bird=Bird()obj_spr=sparrow()obj_ost=ostrich() obj_bird.intro()obj_bird.flight() obj_spr.intro()obj_spr.flight() obj_ost.intro()obj_ost.flight()OutputTherearemanytypesofbirds. Mostofthebirdscanflybutsomecannot. Therearemanytypesofbirds. Sparrowscanfly. Therearemanytypesofbirds. Ostrichescannotfly.Note:Formoreinformation,refertoourPolymorphisminPythonTutorial.EncapsulationEncapsulationisoneofthefundamentalconceptsinobject-orientedprogramming(OOP).Itdescribestheideaofwrappingdataandthemethodsthatworkondatawithinoneunit.Thisputsrestrictionsonaccessingvariablesandmethodsdirectlyandcanpreventtheaccidentalmodificationofdata.Topreventaccidentalchange,anobject’svariablecanonlybechangedbyanobject’smethod.Thosetypesofvariablesareknownasprivatevariables.Aclassisanexampleofencapsulationasitencapsulatesallthedatathatismemberfunctions,variables,etc.Example:EncapsulationinPythonPython3#Pythonprogramto#demonstrateprivatemembers #CreatingaBaseclassclassBase:    def__init__(self):        self.a="GeeksforGeeks"        self.__c="GeeksforGeeks" #CreatingaderivedclassclassDerived(Base):    def__init__(self):         #Callingconstructorof        #Baseclass        Base.__init__(self)        print("Callingprivatememberofbaseclass:")        print(self.__c)  #Drivercodeobj1=Base()print(obj1.a) #Uncommentingprint(obj1.c)will#raiseanAttributeError #Uncommentingobj2=Derived()will#alsoraiseanAtrributeErroras#privatememberofbaseclass#iscalledinsidederivedclassOutputGeeksforGeeksIntheaboveexample,wehavecreatedthecvariableastheprivateattribute.Wecannotevenaccessthisattributedirectlyandcan’tevenchangeitsvalue.Note:formoreinformation,refertoourEncapsulationinPythonTutorial.DataAbstraction Ithidestheunnecessarycodedetailsfromtheuser.Also, whenwedonotwanttogiveoutsensitivepartsofourcodeimplementationandthisiswheredataabstractioncame.DataAbstractioninPythoncanbeachievedthroughcreatingabstractclasses.ObjectOrientedProgramminginPython|Set2(DataHidingandObjectPrinting)https://youtu.be/CiH7lN4Pleasewritecommentsifyoufindanythingincorrect,oryouwanttosharemoreinformationaboutthetopicdiscussedaboveMyPersonalNotes arrow_drop_upSave LikeNext ObjectOrientedProgramminginPython|Set2(DataHidingandObjectPrinting)RecommendedArticlesPage:06,Oct2007,Jun2217,Sep2117,Jun1925,Feb1631,Jul1906,Jun1911,Jun1911,Jun1912,Jun1917,Aug1902,Sep1926,Sep1904,Mar2021,Apr2026,Apr2028,May2031,Jul2013,Aug2015,Aug2002,Jan2116,Dec2116,Dec2109,Feb16ArticleContributedBy:GeeksforGeeksVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:tripathipriyanshu1998nikhilaggarwal3Kushagravatsaraj095907ArticleTags:python-oop-conceptsPythonPracticeTags:pythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?