Polymorphism in Python - GeeksforGeeks

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

In Python, Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class. 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 ▲RelatedArticlesIntroductionPythonProgrammingLanguageIntroductionToPYTHONPythonLanguageadvantagesandapplicationsDownloadandInstallPython3LatestVersionPython3basicsPythonKeywordsNamespacesandScopeinPythonStatement,IndentationandCommentinPythonHowtoassignvaluestovariablesinPythonandotherlanguagesInput/OutputTakinginputinPythonTakinginputfromconsoleinPythonTakingmultipleinputsfromuserinPythonPython|Outputusingprint()functionHowtoprintwithoutnewlineinPython?Pythonendparameterinprint()Python|sepparameterinprint()Python|OutputFormattingOperatorsPythonOperatorsTernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1OperatorFunctionsinPython|Set2Differencebetween==andisoperatorinPythonPythonMembershipandIdentityOperatorsDataTypesPython|Set3(Strings,Lists,Tuples,Iterations)PythonStringPythonListsPythonTuplesPythonSetsPythonDictionaryPythonArraysControlFlowControlFlowinPythonChainingcomparisonoperatorsinPythonPythonForLoopsPythonWhileLoopPythonbreakstatementPythonContinueStatementPythonpassStatementLoopingTechniquesinPythonFunctionsPythonFunctions*argsand**kwargsinPythonWhentouseyieldinsteadofreturninPython?GeneratorsinPythonPythonlambdaGlobalandLocalVariablesinPythonGlobalkeywordinPythonFirstClassfunctionsinPythonPythonClosuresDecoratorsinPythonDecoratorswithparametersinPythonMemoizationusingdecoratorsinPythonPythonOOPPythonClassesandObjectsConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonClassorStaticVariablesinPythonClassmethodvsStaticmethodinPythonExceptionHandlingPythonExceptionHandlingPythonTryExceptErrorsandExceptionsinPythonBuilt-inExceptionsinPythonUser-definedExceptionsinPythonwithExamplesNZECerrorinPythonFilehandlingFileHandlinginPythonOpenaFileinPythonHowtoreadfromafileinPythonWritingtofileinPythonPythonappendtoafilePythonRegexRegularExpressioninPythonwithExamples|Set1RegularExpressionsinPython–Set2(Search,MatchandFindAll)PythonRegex:re.search()VSre.findall()VerboseinPythonRegexPasswordvalidationinPythonPythonCollectionsPythonCollectionsModuleCountersinPython|Set1(InitializationandUpdation)OrderedDictinPythonDefaultdictinPythonChainMapinPythonNamedtupleinPythonDequeinPythonHeapqueue(orheapq)inPythonCollections.UserDictinPythonCollections.UserListinPythonCollections.UserStringinPythonPythonAdvanceOSModuleinPythonwithExamplesFunctionalProgramminginPythonMetaprogrammingwithMetaclassesinPythonAbstractClassesinPythonMultithreadinginPython|Set1MultithreadinginPython|Set2(Synchronization)MultiprocessinginPython|Set1(Introduction)MultiprocessinginPython|Set2(Communicationbetweenprocesses)SocketProgramminginPythonSocketProgrammingwithMulti-threadinginPythonPythonNumPyNumPyTutorialPythonNumpyNumpy|ndarrayNumpy|ArrayCreationNumpy|IndexingBasicSlicingandAdvancedIndexinginNumPyPythonNumpy|DataTypeObjectsNumpy|IteratingOverArrayNumpy|BinaryOperationsNumpy|MathematicalFunctionNumpy|StringOperationsNumpy|LinearAlgebraNumpy|Sorting,SearchingandCountingRandomsamplinginnumpy|randint()functionRandomsamplinginnumpy|random_sample()functionRandomsamplinginnumpy|ranf()functionRandomsamplinginnumpy|random_integers()functionNumpyufunc|UniversalfunctionsPythonPandasPandasTutorialIntroductiontoPandasinPythonHowtoInstallPythonPandasonWindowsandLinux?Python|PandasDataFrameCreatingaPandasDataFramePython|PandasSeriesCreatingaPandasSeriesPython|PandasDataframe/Series.head()methodPython|PandasDataframe.describe()methodDealingwithRowsandColumnsinPandasDataFramePython|PandasExtractingrowsusing.loc[]Python|ExtractingrowsusingPandas.iloc[]IndexingandSelectingDatawithPandasBooleanIndexinginPandasPandasGroupByPython|PandasMerging,Joining,andConcatenatingPython|WorkingwithdateandtimeusingPandasPython|PandasWorkingWithTextDataPython|Readcsvusingpandas.read_csv()Python|WorkingwithPandasandXlsxWriter|Set–1PythonDjangoDjangoTutorialDjangoBasicsDjangoIntroductionandInstallationDjangoProjectMVTStructureHowtoCreateaBasicProjectusingMVTinDjango?HowtoCreateanAppinDjango?DjangoFormsRenderHTMLForms(GET&POST)inDjangoDjangoformfieldcustomwidgetsDjangoModelForm–CreateformfromModelsDjangoFormsetsDjangoModelFormSetsDjangoTemplatesViewsInDjango|PythonDjangoCRUD(Create,Retrieve,Update,Delete)FunctionBasedViewsClassBasedGenericViewsDjango(Create,Retrieve,Update,Delete)DjangoModelsDjangoORM–Inserting,Updating&DeletingDataDjangoBasicAppModel–MakemigrationsandMigratePythonJSONPythonJSONWorkingWithJSONDatainPythonRead,WriteandParseJSONusingPythonAppendtoJSONfileusingPythonSerializingJSONdatainPythonDeserializeJSONtoObjectinPythonPythonCSVWorkingwithcsvfilesinPythonReadingCSVfilesinPythonWritingCSVfilesinPythonPythonMySQLPythonMySQLConnectMySQLdatabaseusingMySQL-ConnectorPythonPythonMySQL–CreateDatabasePython:MySQLCreateTablePythonMySQL–InsertintoTablePythonMySQL–SelectQueryPythonMySQL–WhereClausePythonMySQL–OrderByClausePythonMySQL–DeleteQueryPythonMySQL–DropTablePythonMySQL–UpdateQueryPythonMySQL–LimitClausePythonMySQL–JoinPythonMongoDBPythonMongoDBTutorialInstallingMongoDBonWindowswithPythonMongoDBandPythonCreateadatabaseinMongoDBusingPythonPythonMongoDB–insert_oneQueryPythonMongoDB–insert_manyQueryPythonMongoDB–FindPythonMongoDB–QueryPythonMongoDB–SortMongoDBpython|DeleteDataandDropCollectionPythonMongodb–Delete_one()PythonMongodb–Delete_many()PythonMongoDB–Update_one()PythonMongoDB–Update_manyQueryPythonMongoDB–LimitQueryPythonMongoDB–create_indexQueryPythonMongoDB–drop_indexQueryPythonOpenCVOpenCVPythonTutorialIntroductiontoOpenCVHowtoInstallOpenCVforPythononWindows?ReadinganimageinOpenCVusingPythonOpenCV|SavinganImageArithmeticOperationsonImagesusingOpenCV|Set-1(AdditionandSubtraction)ArithmeticOperationsonImagesusingOpenCV|Set-2(BitwiseOperationsonBinaryImages)ImageResizingusingOpenCV|PythonImageProcessinginPython(Scaling,Rotating,ShiftingandEdgeDetection)Python|ImageblurringusingOpenCVErosionandDilationofimagesusingOpenCVinpythonPython|ThresholdingtechniquesusingOpenCV|Set-1(SimpleThresholding)Python|ThresholdingtechniquesusingOpenCV|Set-2(AdaptiveThresholding)Python|ThresholdingtechniquesusingOpenCV|Set-3(OtsuThresholding)FilterColorwithOpenCVPython|BilateralFilteringPython|BackgroundsubtractionusingOpenCVPython|PlayavideousingOpenCVExtractimagesfromvideoinPythonFaceDetectionusingPythonandOpenCVwithwebcamPythonSeleniumSeleniumPythonTutorialSeleniumBasics–Components,Features,UsesandLimitationsComponentsofSeleniumSeleniumPythonIntroductionandInstallationNavigatinglinksusinggetmethod–SeleniumPythonInteractingwithWebpage–SeleniumPythonLocatingsingleelementsinSeleniumPythonLocatingmultipleelementsinSeleniumPythonLocatorStrategies–SeleniumPythonActionChainsinSeleniumPythonExceptions–SeleniumPythonPythonTkinterPythonTkinterTutorialIntroductiontoTkinterWhatareWidgetsinTkinter?Python|CreatingabuttonintkinterPythonTkinter–LabelRadioButtoninTkinter|PythonPythonTkinter–CheckbuttonWidgetPythonTkinter–CanvasWidgetComboboxWidgetintkinter|PythonPythonTkinter–EntryWidgetPythonTkinter–TextWidgetPythonTkinter–MessagePython|MenuwidgetinTkinterPythonTkinter–SpinBoxProgressbarwidgetinTkinter|PythonPython-TkinterScrollbarPythonTkinter–ScrolledTextWidgetPythonTkinter–ListBoxWidgetPythonTkinter–FrameWidgetPythonTkinter–ScaleWidgetHierarchicaltreeviewinPythonGUIapplicationPython-TkinterTreeviewscrollbarPythonTkinter–ToplevelWidgetPython|askopenfile()functioninTkinterPython|asksaveasfile()functioninTkinterPython–TkinteraskquestionDialogPythonTkinter–MessageBoxWidgetPython|place()methodinTkinterPython|grid()methodinTkinterPython|pack()methodinTkinterPython|PanedWindowWidgetinTkinterPython|BindingfunctioninTkinterPythonTkinter–ValidatingEntryWidgetPythonKivyKivyTutorialIntroductiontoKivy;ACross-platformPythonFrameworkPython|AddLabeltoakivywindowPython|TextinputwidgetinkivyPython|CanvasinkivyPython|CheckboxwidgetinKivyPython|DropdownlistinkivyPython|CarouselWidgetInKivyPython|BoxLayoutwidgetinKivyPython|SliderwidgetinKivyPython|PopupwidgetinKivyPython|SwitchwidgetinKivyPython|SpinnerwidgetinkivyPython|ProgressBarwidgetinkivyPython|WorkingwithbuttonsinKivyPython|FloatLayoutinKivyGridLayoutsinKivy|PythonPython|StackLayoutinKivyPython|AnchorLayoutinKivyPython|RelativeLayoutinKivyPython|PageLayoutinKivyDataVisualizationMatplotlibTutorialPythonSeabornTutorialPythonPlotlytutorialPythonBokehtutorial–InteractiveDataVisualizationwithBokehTableauTutorialPythonExamplesandQuizPythonProgrammingExamplesPythonExercises,PracticeQuestionsandSolutionsPythonMultipleChoiceQuestionsIntroductionPythonProgrammingLanguageIntroductionToPYTHONPythonLanguageadvantagesandapplicationsDownloadandInstallPython3LatestVersionPython3basicsPythonKeywordsNamespacesandScopeinPythonStatement,IndentationandCommentinPythonHowtoassignvaluestovariablesinPythonandotherlanguagesInput/OutputTakinginputinPythonTakinginputfromconsoleinPythonTakingmultipleinputsfromuserinPythonPython|Outputusingprint()functionHowtoprintwithoutnewlineinPython?Pythonendparameterinprint()Python|sepparameterinprint()Python|OutputFormattingOperatorsPythonOperatorsTernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1OperatorFunctionsinPython|Set2Differencebetween==andisoperatorinPythonPythonMembershipandIdentityOperatorsDataTypesPython|Set3(Strings,Lists,Tuples,Iterations)PythonStringPythonListsPythonTuplesPythonSetsPythonDictionaryPythonArraysControlFlowControlFlowinPythonChainingcomparisonoperatorsinPythonPythonForLoopsPythonWhileLoopPythonbreakstatementPythonContinueStatementPythonpassStatementLoopingTechniquesinPythonFunctionsPythonFunctions*argsand**kwargsinPythonWhentouseyieldinsteadofreturninPython?GeneratorsinPythonPythonlambdaGlobalandLocalVariablesinPythonGlobalkeywordinPythonFirstClassfunctionsinPythonPythonClosuresDecoratorsinPythonDecoratorswithparametersinPythonMemoizationusingdecoratorsinPythonPythonOOPPythonClassesandObjectsConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonClassorStaticVariablesinPythonClassmethodvsStaticmethodinPythonExceptionHandlingPythonExceptionHandlingPythonTryExceptErrorsandExceptionsinPythonBuilt-inExceptionsinPythonUser-definedExceptionsinPythonwithExamplesNZECerrorinPythonFilehandlingFileHandlinginPythonOpenaFileinPythonHowtoreadfromafileinPythonWritingtofileinPythonPythonappendtoafilePythonRegexRegularExpressioninPythonwithExamples|Set1RegularExpressionsinPython–Set2(Search,MatchandFindAll)PythonRegex:re.search()VSre.findall()VerboseinPythonRegexPasswordvalidationinPythonPythonCollectionsPythonCollectionsModuleCountersinPython|Set1(InitializationandUpdation)OrderedDictinPythonDefaultdictinPythonChainMapinPythonNamedtupleinPythonDequeinPythonHeapqueue(orheapq)inPythonCollections.UserDictinPythonCollections.UserListinPythonCollections.UserStringinPythonPythonAdvanceOSModuleinPythonwithExamplesFunctionalProgramminginPythonMetaprogrammingwithMetaclassesinPythonAbstractClassesinPythonMultithreadinginPython|Set1MultithreadinginPython|Set2(Synchronization)MultiprocessinginPython|Set1(Introduction)MultiprocessinginPython|Set2(Communicationbetweenprocesses)SocketProgramminginPythonSocketProgrammingwithMulti-threadinginPythonPythonNumPyNumPyTutorialPythonNumpyNumpy|ndarrayNumpy|ArrayCreationNumpy|IndexingBasicSlicingandAdvancedIndexinginNumPyPythonNumpy|DataTypeObjectsNumpy|IteratingOverArrayNumpy|BinaryOperationsNumpy|MathematicalFunctionNumpy|StringOperationsNumpy|LinearAlgebraNumpy|Sorting,SearchingandCountingRandomsamplinginnumpy|randint()functionRandomsamplinginnumpy|random_sample()functionRandomsamplinginnumpy|ranf()functionRandomsamplinginnumpy|random_integers()functionNumpyufunc|UniversalfunctionsPythonPandasPandasTutorialIntroductiontoPandasinPythonHowtoInstallPythonPandasonWindowsandLinux?Python|PandasDataFrameCreatingaPandasDataFramePython|PandasSeriesCreatingaPandasSeriesPython|PandasDataframe/Series.head()methodPython|PandasDataframe.describe()methodDealingwithRowsandColumnsinPandasDataFramePython|PandasExtractingrowsusing.loc[]Python|ExtractingrowsusingPandas.iloc[]IndexingandSelectingDatawithPandasBooleanIndexinginPandasPandasGroupByPython|PandasMerging,Joining,andConcatenatingPython|WorkingwithdateandtimeusingPandasPython|PandasWorkingWithTextDataPython|Readcsvusingpandas.read_csv()Python|WorkingwithPandasandXlsxWriter|Set–1PythonDjangoDjangoTutorialDjangoBasicsDjangoIntroductionandInstallationDjangoProjectMVTStructureHowtoCreateaBasicProjectusingMVTinDjango?HowtoCreateanAppinDjango?DjangoFormsRenderHTMLForms(GET&POST)inDjangoDjangoformfieldcustomwidgetsDjangoModelForm–CreateformfromModelsDjangoFormsetsDjangoModelFormSetsDjangoTemplatesViewsInDjango|PythonDjangoCRUD(Create,Retrieve,Update,Delete)FunctionBasedViewsClassBasedGenericViewsDjango(Create,Retrieve,Update,Delete)DjangoModelsDjangoORM–Inserting,Updating&DeletingDataDjangoBasicAppModel–MakemigrationsandMigratePythonJSONPythonJSONWorkingWithJSONDatainPythonRead,WriteandParseJSONusingPythonAppendtoJSONfileusingPythonSerializingJSONdatainPythonDeserializeJSONtoObjectinPythonPythonCSVWorkingwithcsvfilesinPythonReadingCSVfilesinPythonWritingCSVfilesinPythonPythonMySQLPythonMySQLConnectMySQLdatabaseusingMySQL-ConnectorPythonPythonMySQL–CreateDatabasePython:MySQLCreateTablePythonMySQL–InsertintoTablePythonMySQL–SelectQueryPythonMySQL–WhereClausePythonMySQL–OrderByClausePythonMySQL–DeleteQueryPythonMySQL–DropTablePythonMySQL–UpdateQueryPythonMySQL–LimitClausePythonMySQL–JoinPythonMongoDBPythonMongoDBTutorialInstallingMongoDBonWindowswithPythonMongoDBandPythonCreateadatabaseinMongoDBusingPythonPythonMongoDB–insert_oneQueryPythonMongoDB–insert_manyQueryPythonMongoDB–FindPythonMongoDB–QueryPythonMongoDB–SortMongoDBpython|DeleteDataandDropCollectionPythonMongodb–Delete_one()PythonMongodb–Delete_many()PythonMongoDB–Update_one()PythonMongoDB–Update_manyQueryPythonMongoDB–LimitQueryPythonMongoDB–create_indexQueryPythonMongoDB–drop_indexQueryPythonOpenCVOpenCVPythonTutorialIntroductiontoOpenCVHowtoInstallOpenCVforPythononWindows?ReadinganimageinOpenCVusingPythonOpenCV|SavinganImageArithmeticOperationsonImagesusingOpenCV|Set-1(AdditionandSubtraction)ArithmeticOperationsonImagesusingOpenCV|Set-2(BitwiseOperationsonBinaryImages)ImageResizingusingOpenCV|PythonImageProcessinginPython(Scaling,Rotating,ShiftingandEdgeDetection)Python|ImageblurringusingOpenCVErosionandDilationofimagesusingOpenCVinpythonPython|ThresholdingtechniquesusingOpenCV|Set-1(SimpleThresholding)Python|ThresholdingtechniquesusingOpenCV|Set-2(AdaptiveThresholding)Python|ThresholdingtechniquesusingOpenCV|Set-3(OtsuThresholding)FilterColorwithOpenCVPython|BilateralFilteringPython|BackgroundsubtractionusingOpenCVPython|PlayavideousingOpenCVExtractimagesfromvideoinPythonFaceDetectionusingPythonandOpenCVwithwebcamPythonSeleniumSeleniumPythonTutorialSeleniumBasics–Components,Features,UsesandLimitationsComponentsofSeleniumSeleniumPythonIntroductionandInstallationNavigatinglinksusinggetmethod–SeleniumPythonInteractingwithWebpage–SeleniumPythonLocatingsingleelementsinSeleniumPythonLocatingmultipleelementsinSeleniumPythonLocatorStrategies–SeleniumPythonActionChainsinSeleniumPythonExceptions–SeleniumPythonPythonTkinterPythonTkinterTutorialIntroductiontoTkinterWhatareWidgetsinTkinter?Python|CreatingabuttonintkinterPythonTkinter–LabelRadioButtoninTkinter|PythonPythonTkinter–CheckbuttonWidgetPythonTkinter–CanvasWidgetComboboxWidgetintkinter|PythonPythonTkinter–EntryWidgetPythonTkinter–TextWidgetPythonTkinter–MessagePython|MenuwidgetinTkinterPythonTkinter–SpinBoxProgressbarwidgetinTkinter|PythonPython-TkinterScrollbarPythonTkinter–ScrolledTextWidgetPythonTkinter–ListBoxWidgetPythonTkinter–FrameWidgetPythonTkinter–ScaleWidgetHierarchicaltreeviewinPythonGUIapplicationPython-TkinterTreeviewscrollbarPythonTkinter–ToplevelWidgetPython|askopenfile()functioninTkinterPython|asksaveasfile()functioninTkinterPython–TkinteraskquestionDialogPythonTkinter–MessageBoxWidgetPython|place()methodinTkinterPython|grid()methodinTkinterPython|pack()methodinTkinterPython|PanedWindowWidgetinTkinterPython|BindingfunctioninTkinterPythonTkinter–ValidatingEntryWidgetPythonKivyKivyTutorialIntroductiontoKivy;ACross-platformPythonFrameworkPython|AddLabeltoakivywindowPython|TextinputwidgetinkivyPython|CanvasinkivyPython|CheckboxwidgetinKivyPython|DropdownlistinkivyPython|CarouselWidgetInKivyPython|BoxLayoutwidgetinKivyPython|SliderwidgetinKivyPython|PopupwidgetinKivyPython|SwitchwidgetinKivyPython|SpinnerwidgetinkivyPython|ProgressBarwidgetinkivyPython|WorkingwithbuttonsinKivyPython|FloatLayoutinKivyGridLayoutsinKivy|PythonPython|StackLayoutinKivyPython|AnchorLayoutinKivyPython|RelativeLayoutinKivyPython|PageLayoutinKivyDataVisualizationMatplotlibTutorialPythonSeabornTutorialPythonPlotlytutorialPythonBokehtutorial–InteractiveDataVisualizationwithBokehTableauTutorialPythonExamplesandQuizPythonProgrammingExamplesPythonExercises,PracticeQuestionsandSolutionsPythonMultipleChoiceQuestionsPolymorphisminPythonViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 04Aug,2021ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle WhatisPolymorphism:Thewordpolymorphismmeanshavingmanyforms.Inprogramming,polymorphismmeansthesamefunctionname(butdifferentsignatures)beingusedfordifferenttypes.Exampleofinbuiltpolymorphicfunctions:  Python3#Pythonprogramtodemonstratein-builtpoly-#morphicfunctions #len()beingusedforastringprint(len("geeks")) #len()beingusedforalistprint(len([10,20,30]))Output: 5 3 Examplesofuser-definedpolymorphicfunctions:  Python3#AsimplePythonfunctiontodemonstrate#Polymorphism defadd(x,y,z=0):    returnx+y+z #Drivercodeprint(add(2,3))print(add(2,3,4))Output: 5 9 Polymorphismwithclassmethods: ThebelowcodeshowshowPythoncanusetwodifferentclasstypes,inthesameway.Wecreateaforloopthatiteratesthroughatupleofobjects.Thencallthemethodswithoutbeingconcernedaboutwhichclasstypeeachobjectis.Weassumethatthesemethodsactuallyexistineachclass.  Python3classIndia():    defcapital(self):        print("NewDelhiisthecapitalofIndia.")     deflanguage(self):        print("HindiisthemostwidelyspokenlanguageofIndia.")     deftype(self):        print("Indiaisadevelopingcountry.") classUSA():    defcapital(self):        print("Washington,D.C.isthecapitalofUSA.")     deflanguage(self):        print("EnglishistheprimarylanguageofUSA.")     deftype(self):        print("USAisadevelopedcountry.") obj_ind=India()obj_usa=USA()forcountryin(obj_ind,obj_usa):    country.capital()    country.language()    country.type()Output: NewDelhiisthecapitalofIndia. HindiisthemostwidelyspokenlanguageofIndia. Indiaisadevelopingcountry. Washington,D.C.isthecapitalofUSA. EnglishistheprimarylanguageofUSA. USAisadevelopedcountry.  PolymorphismwithInheritance: InPython,Polymorphismletsusdefinemethodsinthechildclassthathavethesamenameasthemethodsintheparentclass.Ininheritance,thechildclassinheritsthemethodsfromtheparentclass.However,itispossibletomodifyamethodinachildclassthatithasinheritedfromtheparentclass.Thisisparticularlyusefulincaseswherethemethodinheritedfromtheparentclassdoesn’tquitefitthechildclass.Insuchcases,were-implementthemethodinthechildclass.Thisprocessofre-implementingamethodinthechildclassisknownasMethodOverriding.  Python3classBird:  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()Output: Therearemanytypesofbirds. Mostofthebirdscanflybutsomecannot. Therearemanytypesofbirds. Sparrowscanfly. Therearemanytypesofbirds. Ostrichescannotfly.  PolymorphismwithaFunctionandobjects: Itisalsopossibletocreateafunctionthatcantakeanyobject,allowingforpolymorphism.Inthisexample,let’screateafunctioncalled“func()”whichwilltakeanobjectwhichwewillname“obj”.Thoughweareusingthename‘obj’,anyinstantiatedobjectwillbeabletobecalledintothisfunction.Next,let’sgivethefunctionsomethingtodothatusesthe‘obj’objectwepassedtoit.Inthiscase,let’scallthethreemethods,viz.,capital(),language()andtype(),eachofwhichisdefinedinthetwoclasses‘India’and‘USA’.Next,let’screateinstantiationsofboththe‘India’and‘USA’classesifwedon’thavethemalready.Withthose,wecancalltheiractionusingthesamefunc()function:  Python3deffunc(obj):    obj.capital()    obj.language()    obj.type()  obj_ind=India()obj_usa=USA()  func(obj_ind)func(obj_usa)  Code:ImplementingPolymorphismwithaFunction  Python3classIndia():    defcapital(self):        print("NewDelhiisthecapitalofIndia.")      deflanguage(self):        print("HindiisthemostwidelyspokenlanguageofIndia.")      deftype(self):        print("Indiaisadevelopingcountry.")  classUSA():    defcapital(self):        print("Washington,D.C.isthecapitalofUSA.")      deflanguage(self):        print("EnglishistheprimarylanguageofUSA.")      deftype(self):        print("USAisadevelopedcountry.") deffunc(obj):    obj.capital()    obj.language()    obj.type()  obj_ind=India()obj_usa=USA()  func(obj_ind)func(obj_usa)Output: NewDelhiisthecapitalofIndia. HindiisthemostwidelyspokenlanguageofIndia. Indiaisadevelopingcountry. Washington,D.C.isthecapitalofUSA. EnglishistheprimarylanguageofUSA. USAisadevelopedcountry. MyPersonalNotes arrow_drop_upSave LikePreviousEncapsulationinPythonNext ClassorStaticVariablesinPythonRecommendedArticlesPage:22,Sep2025,Feb1631,Jul1906,Jun1911,Jun1911,Jun1912,Jun1917,Aug1902,Sep1926,Sep1904,Mar2021,Apr2026,Apr2028,May2031,Jul2013,Aug2015,Aug2002,Jan2116,Dec2116,Dec2109,Feb1603,Jan2128,Oct2124,Jul18ArticleContributedBy:Rahul_Roy@Rahul_RoyVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:VeeraVeeraprakashmichaelrollinsArticleTags:PickedPython-Functionspython-inheritancePython-OOPpython-oop-conceptsTechnicalScripter2018PythonTechnicalScripterPracticeTags:pythonpython-functionsReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?