How to Provide Multiple Constructors in Python Classes
文章推薦指數: 80 %
One method that is quite useful to simulate multiple constructors within the Python class would be to supply .__init__() with optional arguments by using ... ⇧SCROLLTOTOP Home Python IfElse ForLoop Function Array String Regex List Set Tuple Dictionary Programs Numpy InterviewQuestions PythonTutorial PythonTutorial PythonFeatures PythonHistory PythonApplications PythonInstall PythonExample PythonVariables PythonDataTypes PythonKeywords PythonLiterals PythonOperators PythonComments PythonIfelse PythonLoops PythonForLoop PythonWhileLoop PythonBreak PythonContinue PythonPass PythonStrings PythonLists PythonTuples PythonListVsTuple PythonSets PythonDictionary PythonFunctions PythonBuilt-inFunctions PythonLambdaFunctions PythonFilesI/O PythonModules PythonExceptions PythonDate PythonRegex PythonSendingEmail ReadCSVFile WriteCSVFile ReadExcelFile WriteExcelFile PythonAssert PythonListComprehension PythonCollectionModule PythonMathModule PythonOSModule PythonRandomModule PythonStatisticsModule PythonSysModule PythonIDEs PythonArrays CommandLineArguments PythonMagicMethod PythonStack&Queue PySparkMLlib PythonDecorator PythonGenerators WebScrapingUsingPython PythonJSON PythonItertools PythonMultiprocessing HowtoCalculateDistancebetweenTwoPointsusingGEOPY GmailAPIinPython HowtoPlottheGoogleMapusingfoliumpackageinPython GridSearchinPython PythonHighOrderFunction nsetoolsinPython PythonprogramtofindthenthFibonacciNumber PythonOpenCVobjectdetection PythonSimpleImputermodule SecondLargestNumberinPython PythonOOPs PythonOOPsConcepts PythonObjectClass PythonConstructors PythonInheritance AbstractioninPython PythonMySQL EnvironmentSetup DatabaseConnection CreatingNewDatabase CreatingTables InsertOperation ReadOperation UpdateOperation JoinOperation PerformingTransactions PythonMongoDB PythonMongoDB PythonSQLite PythonSQLite PythonQuestions HowtoinstallPythoninWindows HowtoreverseastringinPython HowtoreadCSVfileinPython HowtorunPythonProgram HowtotakeinputinPython HowtoconvertlisttostringinPython Howtoappendelementinthelist HowtocomparetwolistsinPython HowtoconvertinttostringinPython HowtocreateadictionaryinPython HowtocreateavirtualenvironmentinPython HowtodeclareavariableinPython HowtoinstallmatplotlibinPython HowtoinstallOpenCVinPython HowtoprintinsamelineinPython HowtoreadJSONfileinPython HowtoreadatextfileinPython HowtouseforloopinPython IsPythonscriptinglanguage HowlongdoesittaketolearnPython HowtoconcatenatetwostringsinPython HowtoconnectDatabaseinPython HowtoconvertlisttodictionaryinPython HowtodeclareaglobalvariableinPython HowtoreverseanumberinPython WhatisanobjectinPython WhichisthefastestimplementationofPython HowtoclearPythonshell HowtocreateaDataFramesinPython HowtodevelopagameinPython HowtoinstallTkinterinPython HowtoplotagraphinPython HowtoprintpatterninPython HowtoremoveanelementfromalistinPython HowtoRoundnumberinPython HowtosortadictionaryinPython StrongNumberinPython HowtoConvertTexttoSpeechinPython BubbleSortinPython LogginginPython InsertionSortinPython BinarySearchinPython LinearSearchinPython PythonvsScala QueueinPython StackinPython HeapSortinPython Palindromeprograminpython ProgramofCumulativesuminpython MergeSortinPython PythonMatrix PythonUnitTesting Forensics&Virtualization BestBookstoLearnPython BestBookstoLearnDjango GCDoftwonumberinpython PythonProgramtogenerateaRandomString HowtoOneHotEncodeSequenceDatainPython HowtowritesquarerootinPython PointerinPython Python2Darray PythonMemoryManagement PythonLibrariesforDataVisualization HowtocallafunctioninPython GitModulesinPython TopPythonFrameworksforGaming PythonAudioModules WikipediaModuleinPython Pythonrandomrandrange() PermutationandCombinationinPython GetoptmoduleinPython MergetwoDictionariesinPython MultithreadinginPython3 StaticinPython HowtogetthecurrentdateinPython argparseinPython PythontqdmModule CaesarCipherinPython TokenizerinPython HowtoaddtwolistsinPython ShallowCopyandDeepCopyinPython AtomPython ContainsinPython LabelEncodinginPython Djangovs.NodeJS PythonFrameworks HowtocreateavectorinPythonusingNumPy PickleModuleofPython HowtoconvertBytestostringinPython PythonProgramtoFindAnagram HowtoconvertListtoSet PythonvsJavaScript PythonHolidaysModule FuzzyWuzzyPythonLibrary DaskPython DaskPython(Part2) ModeinPython Menu-DrivenProgramsinPython PythonArrayvs.List WhatisducktypinginPython PEP8inPython PythonUserGroups BasicCommandsinPython FStringinPython HowBrythonWorks HowtouseBrythonintheBrowser ArimaModelinPython PythonModulusOperator MATLABvs.Python MethodResolutionOrderinPython MonkeyPatchinginPython Python__call__method Pythonheapqmodule PythonSubstring ProjectideasforPythonBeginners PythonFaker Fizz-BuzzPrograminPython TabulaPython PythonProgramtoPrintPrimeFactorofGivenNumber PythonProgramtoPrintPascalTriangle NamedTupleinPython OrderedDictinPython T-TestinPython Pythonreturnstatement GetterandSetterinPython EnumclassinPython DestructorsinPython CurveFitinPython ConvertingCSVtoJSONinPython Underscore(_)inPython SetvsListinPython LocatingandExecutingModules FlattenListinPython PairPlotinPython DataHidinginPython PythonProgramtoFindIntersectionofTwoLists HowtoCreateRequirements.txtFileinPython Tic-Tac-ToeinPython PythonAsynchronousProgramming-asyncioandawait Pythonmain()function strftime()functioninPython VerboseFlaginPythonRegex PythonASTModule PythonRequestsModule-HTTPRequest ShutilModuleinPython PythonepochtoDatetime PythondelStatement LoopingtechniqueinPython MetaprogrammingwithMetaclassesinPython PrecisionHandlinginPython PythonJoinList strip()functioninPython GradientDescentAlgorithm PrettytableinPython SentimentAnalysisinPython ConvertPythonListtoNumPyArrays TracebackinPython Timeclock()MethodinPython DequeinPython DictionaryComprehensioninPython PythonDataAnalytics Pythonseek()Method TernaryOperatorinPython HowtoCalculatetheAreaoftheCircleusingPython HowtoWriteinTextFileusingPython PythonKeyError Pythonsuper()Function max()functioninPython FractionModuleinPython PopularPythonFrameworktoBuildAPI HowtoCheckPythonversion Python%s-StringFormatting PythonseabornLibrary CountplotinPython range()Vs.Xrange()Python WordcloudPackageinPython Convertdataframeintolist ANOVATestinPython Pythonprogramtofindcompoundinterest AnsibleinPython PythonImportantTipsandTricks PythonCoroutines DoubleUnderscoresinPython re.search()VSre.findall()inPythonRegex HowtoinstallstatsmodelsinPython CosinPython vifinPython __add__MethodinPython EthicalHackingwithPython ClassVariablevsInstance PerfectNumberinPython EOLinPython PythonProgramtoconvertHexadecimalStringtoDecimalString DifferentMethodsinPythonforSwappingTwoNumberswithoutusingthirdvariable HowtoChangePlotSizeinMatplotlib HowtoGettheZipCodeinPython EelinPython AssignmentOperatorsinPython SpeechRecognitionpython YieldvsReturninPython GraphenePython NameManglinginPython Pythoncombinationwithoutitertools PythonComprehensions InfluxDBinPython KafkaTutorialinPython AugmentedAssignmentExpressionsinPython Python(x,y)Software PythonEvent-Drivenprogramming PythonSemaphore Pythonsortedreverse AutomorphicNumberinPython sizeofinPython PythonProgramforacceptingthestringswhichcontainsallvowels Class-basedviewsvsFunction-BasedViews HowtohandlecookiesinDjango agg()functioninPython AmicableNumbersinPython ContextManagerinPython CreateBMICalculatorusingPython StringtoBinaryinPython WhatisscriptmodeinPython BestPythonlibrariesforMachineLearning PythonProgramtoDisplayCalendarofGivenYear HowtoopenURLinPython BrokenPipeErrorinPython CodeTemplateforCreatingObjectsinPython Pythonprogramtocalculatethebesttimetobuyandsellstock TupletoStringinPython Kadane'sAlgorithminPython LoggersinDjango WeatherAppinDjango MissingDataConundrum:ExplorationandImputationTechniques DifferentMethodsofArrayRotationinPython WhatisOperatorOverloadinginPython DefaultdictinPython OperatorModuleinPython SpinnerWidgetinthekivyLibraryofPython NumberPlateRecognitionusingPython ObfuscatingaPythonprogram ConvertstringtodictionaryinPython ConvertstringtoJSONinPython DBSCANalgorithminPython HowtoWriteaCodeforPrintingthePythonException/ErrorHierarchy PrincipalComponentAnalysis(PCA)withPython PythonProgramtoFindNumberofDaysBetweenTwoGivenDates ObjectRecognitionusingPython PythonVLCmodule SettolistinPython StringtointinPython InternetofThingswithPython Pythonpysftpmodule AmazinghacksofPython AverageoflistinPython CheckInstalledModulesinPython choice()inPython ConvertListtodataframeinPython ConvertStringtoFloatinPython DecoratorswithParametersinPython DynamicTypinginPython FabsinPython HowtoRemoveDecimalinPython PythonClosure PythonGlobModule WritingaPythonModule ModulesvsPackagesinPython SNMPmoduleinPython AverageoflistinPython AppendvsExtendvsInsertinPython HowtoRemoveDuplicatesfromalistinPython RemoveMultipleCharactersfromaStringinPython ShuffleinPython floor()andceil()FunctionsinPython sqrt():MathFunctionofPython PythonyfinanceModule DifflibmoduleinPython ConverttheColumnTypefromStringtoDatetimeFormatinPandasDataFrame PythonwxPythonModule RandomUniformPython RelationalOperatorsinPython StringtoListinPython ChatbotinPython HowtoConvertfloattointinPython MultiplyAllElementsinlistofPython modulevsfunctioninPython ReverseatupleinPython TupletoDictionaryinPython datetime.timedelta()FunctionofPython PythonBioModule PythonDashModule HowtoSelectrowsinPandasDataFrameBasedonConditions TypecastinginPython DateutilmoduleinPython GetpassmoduleinPython PythonWandlibrary GenerateaQRCodeusingPython BestPythonPDFLibrary PythonCachetoolsModule PythonCmdparserModule PythonDashmodule PythonEmojiModule PythonNmapModule PythonPyLabModule WorkingwithPDFfilesinPython PDFHandlinginPython ManipulatingPDFusingPython ListAllFunctionsfromaPythonModule PythonlistofDictionaries PythonShelveModule CreatingInteractivePDFformsusingPython PythonNewspaperModule HowtoConnectWi-FiusingPython BestPythonLibrariesusedforEthicalHacking WindowsSystemAdministrationManagementusingPython IndentationErrorinPython PythonimaplibModule PythonlxmlModule PythonMayaViModule Pythonos.listdir()method PythonModulesforAutomation DataVisualizationinPythonusingBokehLibrary HowtoPlotglyphsoveraGoogleMapbyusingBokehLibraryinPython HowtoPlotaPieChartusingBokehLibraryinPython HowtoReadContentsofPDFusingOCRinPython GrammarandSpellCheckerinPython ConvertingHTMLtoPDFfilesusingPython ReadlinesinPython HowtoPlotMultipleLinesonaGraphUsingBokehinPython bokeh.plotting.figure.circle_x()FunctioninPython bokeh.plotting.figure.diamond_cross()FunctioninPython HowtoPlotRaysonaGraphusingBokehinPython ImageSteganographyusingPython Inconsistentuseoftabsandspacesinindentation HowtoPlotMultiplePlotsusingBokehinPython HowtoMakeanAreaPlotinPythonusingBokeh PythonChemPyModule Pythonmemory-profilerModule PythonPhonenumbersModule PythonPlatformModule TypeErrorstringindicesmustbeaninteger TimeSeriesForecastingwithProphetinPython PythonPexpectModule PythonOptparseModule intobjectisnotiterable. PythonPeeweeLibrary SomeCryptocurrencyLibrariesforPython BuildingaBlockchainusingPython HuffmanCodingusingPython NestedDictionaryinPython Collections.UserStringinPython HowtoCustomizeLegendswithMatplotlib Matplotliblegendinsubplot MorphologicalOperationsinImageProcessinginPython RoleofPythoninArtificialIntelligence PythonInstagramyModule PythonpprintModule PythonPrimePyModule AndroidDevelopmentusingPython Pythonfbchatlibrary ArtificialIntelligenceinCybersecurity:PittingAlgorithmsvsAlgorithms UnderstandingTheRecognitionPatternofArtificialIntelligence WhenandHowtoLeverageLambdaArchitectureinBigData WhyShouldWeLearnPythonforDataScience HowtoChangethe"legend"PositioninMatplotlib HowtoCheckifElementExistsinListinPython HowtoCheckSpellingsofGivenWordsusingEnchantinPython PythonProgramtoCounttheNumberofMatchingCharactersinaPairofString PingPongGameUsingTurtleinPython PythonFunctiontoDisplayCalendar PythonProgramforCalculatingtheSumofSquaresofFirstnNaturalNumbers PythonProgramforHowtoCheckifaGivenNumberisFibonacciNumberorNot randint()FunctioninPython VisualizeTiffFileusingMatplotlibandGDALinPython rarfilemoduleinPython StemmingWordsusingPython PythonProgramforWordGuessingGame BlockchaininHealthcare:Innovations&Opportunities SnakeGameinPythonusingTurtleModule HowtoFindArmstrongNumbersbetweentwogivenIntegers CeleryTutorialUsingPython RSME-RootMeanSquareErrorinPython BuildingaTwitterBotusingPython PythonProgressbarModule PythonPronouncingModule PythonPyAutoGUIModule PythonPyperclipModule HowtoGenerateUUIDinPython PythonTop10LibrariestoLearnin2022 ReadingNetCDFDatausingPython ThereprlibmoduleinPython HowtotakeMultipleInputfromUserinPython PythonzlibLibrary PythonQueueModule PythonYAMLParser EffectiveRootSearchingAlgorithmsinPython PythonBz2Module PythonIPaddressModule PythonPyLintModule HowtoProcessXMLinPython BisectAlgorithmFunctionsinPython CreatingandUpdatingPowerPointPresentationusingPython Howtochangethesizeoffiguredrawnwithmatplotlib KeyboardModuleinPython PythonPyfigletModule CreatinganMCQQuizGameinPython StatisticwithPython WhatisGILinPython BasicPythonforJavaDevelopers HowtoDownloadYouTubeVideosUsingPythonScripts TrafficFlowSimulationinPython HowtoMergeandSortTwoListsinPython MetacharactersinPython WritethePythonProgramtoPrintAllPossibleCombinationofIntegers ModuloStringFormattinginPython CountersinPython PythonpyautoguiLibrary HowtoDrawtheMandelbrotSetinPython PythonDbmModule WebcamMotionDetectorinPython GraphQLImplementationinDjango HowtoImplementProtobufinPython PyQtlibraryinPython HowtoPrettifyDataStructureswithPrettyPrintinPython EncryptaPasswordinPythonUsingbcrypt PyramidFrameworkinPython BuildingaTelegrambotusingPython Web2pyFrameworkinPython Pythonos.chdir()Method BalancingParenthesesinPython HowtoProvideMultipleConstructorsinPythonClasses ProfilingthePythoncode BuildaDice-RollingApplicationwithPython EmailmoduleinPython EssentialRecursionProgramsinPython HowtoDesignHashsetinPython HowtoExtractYouTubeDatainPython HowtoSolveStockSpanProblemUsingPython SelectionSortinPython info()FunctioninPython TwoSumProblem:PythonSolutionofTwosumproblemofGivenList WriteaPythonProgramtoCheckaListContainsDuplicateElement WritePythonProgramtoSearchanElementinSortedArray PathlibmoduleinPython CreateaRealTimeVoiceTranslatorusingPython HowtoSortTupleinPython AdvantagesofPythonthatmadeitsoPopularanditsMajorApplications LibraryinPython PackagesofDataVisualizationinPython Pythonpymplerlibrary SnakeVizlibraryinPython MaterializedViewvsView NamespaceinPython PythonProgramtoreturntheSignoftheproductofanArray FabricModuleinPython TracemallocmoduleinPython Split,Sub,Subnfunctionsofremoduleinpython RobotFrameworkinPython UnderstandingRoboticswithPython GzipmoduleinPython guppy/heapyinPython MicroservicesinPython FunctoolsModuleinPython PlottingGoogleMapusinggmplotpackageinPython MonitoringDevicesusingPython WebbrowsermoduleinPython BinarySearchusingRecursioninPython CvsC++vsPythonvsJava HowtoCheckVersionofPython PythonListComprehension ConvertRomanNumbertoDecimal(Integer)|WritePythonProgramtoConvertRomantoInteger CreateRESTAPIusingDjangoRESTFramework|DjangoRESTFrameworkTutorial MemoizationusingDecoratorsinPython PythonforNetworkEngineering 'and'vs'&'inPython CryptographypackageinPython HangmanGameinPython ImplementationofLinearRegressionusingPython NestedDecoratorsinPython PythonProgramtoFindDifferencebetweenTwoStrings PythonurllibLibrary FionamoduleinPython Firebasemoduleinpython PythonForKids FloorDivisioninPython Top10BestCourseraPythonCourses TopPythonforNetworkEngineeringLibraries HowdoesTokenizingText,Sentence,WordsWorks HowtoImportDatasetsusingsklearninPyBrain PartofSpeechTaggingusingTextBlob PythonforKids:ResourcesforPythonLearningPath XGBoostMLModelinPython SimpleFLAMESgameinPython AlarmClockwithGUIinPython RockPaperScissorsGameinPython CheckifaGivenLinkedListisCircularLinkedList ReversetheLinkedListinPython Flatten()vsRavel()NumpyFunctions LearningVectorQuantization LemmatizationandTokenizewithTextBlob HowtoRoundNumbersinPython PrecedenceandAssociativityofOperatorsinPython Pythonunofficiallibraries 12BestPythonProjectsforClass12 DesktopNotifierinPython HowtohandleTimezonesinPython PythonSecretModule MakeNotepadusingTkinter CamelcaseinPython DifferencebetweenPythonandScala HowtoUseCbindinPython PythonAsserts PythonBitwiseOperators PythonTimeasctime()Method Q-LearninginPython CombinatoricIteratorsinPython ClassMethodvsStaticMethodvsInstanceMethod FreePythoneBooks EightAmazingIdeasofPythonTkinterProjects CreatingaKeyloggerusingPython QuandlpackageinPython ImplementingAprioriAlgorithminPython SentimentAnalysisusingVADER BreakStatementinPython HandlingImbalancedDatainPythonwithSMOTEAlgorithmandNearMissAlgorithm GUICalculatorusingPython Sympymoduleinpython SmotePython Breadth-FirstSearchinPython PythonGraphviz:DOTLanguage HowtoVisualizeaNeuralNetworkinPythonusingGraphviz PythonGraphviz CompoundInterestGUICalculatorusingPython Rank-basedPercentileGUICalculatorinPython URLshortnerinPython AutomateInstagramMessagesusingPython PythonSimpleHTTPServerModule StandardGUIUnitConverterinPython PythonParamikoModule DispatchDecoratorsinPython IntrospectioninPython ClassDecoratorinPython CustomizingParserBehaviourPythonModule'configparser' Python'sModuleConfigparser GUICalendarusingTkinterinPython PythonProgramtoRotateanImage ValidatetheIPAddressinPython WriteaProgramtoPrinttheDiagonalElementsoftheGiven2DMatrix EncapsulationinPython PolymorphisminPython StringIOModuleinPython 10PythonImageManipulationTools Howtoinsertcurrent_timestampintoPostgresviaPython HowtoPerformaOne-WayANOVAinPython TypesofinheritancePython PythonForMechanicalEngineers PythonModulexxHash EscapeSequencesinPython PYTHONNULLSTATEMENT PythonANDOperator PythonOROperator PythonBitwiseXOROperator PythonNewLine __init__inpython __dict__inPython SimpleTo-DoListGUIApplicationinPython AutomateSoftwareTestingwithPython AutomatetheGooglesearchusingPython __name__inPython _name__main_inPython 8PuzzleprobleminPython accuracy_scoreinSklearn Pythonvs.Julia PythonCrontabModule PythonExecuteShellCommand FileExplorerusingTkinterinPython AutomatedTradinginPython PythonAutomationProjectIdeas K-means1DclusteringinPython Addingakey:valuepairtoadictionaryinPython fit(),transform()andfit_transform()MethodsinPython PythonForFinance LibrosaLibraryinPython PythonArtificialIntelligenceProjectsforBeginners AgeCalculatorusingTkinterinPython HowtoIterateaDictionaryinPython HowtoIteratethroughaListinPython HowtoLearnPythonOnline Cross-ValidationinSklearn PopularPythonLibrariesforFinanceIndustry FamousPythonCertification,CoursesforFinance Accuracy_ScoreinSklearn K-FoldCross-ValidationinSklearn PythonProjectsonMLApplicationsinFinance DigitalClockusingTkinterinPython PlotCorrelationMatrixinPython EuclidianDistanceusingNumPy HowtoParseJSONinPython HowtoMaketheFirstColumnanIndexinPython HowtoMakeanAppinPython MorseCodeTranslatorInPython PythonLocustModule PythonTimeModule SklearnLinearRegressionExample PythonTimeitModule QRcodeusingpython FlippingTiles(Memorygame)usingPython PythonCurl ExamplesofPythonCurl SklearnModelSelection StandardScalerinSklearn FilterListinPython PythonProjectsinNetworking PythonNetworkX SklearnLogisticRegression WhatisSklearninPython TkinterApplicationtoSwitchBetweenDifferentPageFramesinPython Append(key:value)PairtoDictionary any()inPython ArgumentsandParametersinPython AttributesMeaninginPython DataStructuresandAlgorithmsinPython|Set1 GaussianEliminationinPython LearnPythonfromBestYouTubeChannelsin2022 SklearnClustering SklearnTutorial WhatIsSleepingTimeinPython PythonWord2Vec CreatingtheGUIMarksheetusingTkinterinPython AColourgameusingTkinterinPython SimpleFLAMESgameusingTkinterinPython PythonTkinter(GUI) PythonTkinter TkinterButton TkinterCanvas TkinterCheckbutton TkinterEntry TkinterFrame TkinterLabel TkinterListbox TkinterMenubutton TkinterMenu TkinterMessage TkinterRadiobutton TkinterScale TkinterScrollbar TkinterText TkinterToplevel TkinterSpinbox TkinterPanedWindow TkinterLabelFrame TkinterMessageBox PythonWebBlocker Introduction BuildingPythonScript ScriptDeploymentonLinux ScriptDeploymentonWindows PythonMCQ PythonMCQ PythonMCQPart2 RelatedTutorials NumPyTutorial DjangoTutorial FlaskTutorial PandasTutorial PytorchTutorial PygameTutorial MatplotlibTutorial OpenCVTutorial OpenpyxlTutorial PythonCGI PythonDesignPattern PythonPrograms PythonPrograms next→ ←prev HowtoProvideMultipleConstructorsinPythonClasses Sometimes,wehavetocreateaPythonclasswithdifferentwaysofbuildingobjects.Also,itwouldhelpifauserhadanobjectthathasseveralconstructors.Thistypeofclasscanbeusefulinsituationswherewemustcreateinstancesthatusevarioustypesofarguments.Thetoolsthatallowformultipleconstructorscanhelptowriteflexibleclassesthatcanbeadaptedtothechangingrequirements. InPython,thereareavarietyofmethodsandtoolsthatwecanemploytocreateclasses.Theseincludesimulatingmultipleconstructorsusingoptionalarguments,customizingthecreationthroughclassmethods,andperformingspecialdispatchusingdecorators.Iftheusersarelookingtoknowmoreaboutthesemethodsandtools,thistutorialisforthem. Inthiscourse,wewilllearnto: Makeuseofalternativeargumentargumentsaswellascheckfortypeforasimulationofmultipleconstructors Createmultipleconstructorswithaninbuiltclassmethoddecorator Overloadourclassconstructorsusingthe@singledispatchmethoddecorator Also,theuserswillgetaglimpseintotheinsideofthewayPythoninternallycreatesinstancesofregularclassesandhowcertainstandardlibraryclassesofferseveralconstructors. Tobenefitthemostfromthistutorial,itisrecommendedthattheusershavethebasicsofobject-orientedprogrammingandbeabletodefineclassesusing@classmethod.Additionally,theymusthavesomeexperienceworkingusingdecoratorsinPython. InstantiatingClassesinPython Pythonisaprogramminglanguagethatsupportstheconceptofobject-orientedprogrammingbyprovidingclassesthatareeasytowriteandutilize.Classesaresimilartoplansforobjects,alsoreferredtoasinstances.Justaswecanconstructmultiplehomesfromonedesign,wecouldalsobuildmanyinstancesfromasingleclass.Pythonclassesprovidepowerfulcapabilitiesthatallowustowritebettersoftware. FordefiningaclassusingPython,itisnecessarytodefinethekeywordclasskeyword,followedbytheclass'sname: #DefiningaPersonclass classPerson: def__init__(self,name): self.name=name Pythonisafullsetofspecificmethodsthatwecanemployforourclass.Pythoncallsspecificmethodsthatautomaticallyperformmanydifferenttasksontheinstances.Therearespecificmethodsformakingourobjectiterable.Theycanprovideanappropriatestringrepresentationofourobjects,initializeinstancesattributes,andmuchmore. Themostwell-knowntechniquecanbefoundin.__init__().TheinstanceinitializerreferstothismethodinPython.Itsfunctionistosetupinstances'attributeswiththeappropriatevalueswheneverwecreateaclass. In-Person,the.__init__()method'sfirstargumentisreferredtoasself.Theargumentcontainsthecurrentinstanceorobjectandisimplicitlypassedinthismethod'scall.ThisargumentissharedbyallinstancestechniquethatisimplementedinPython.Thesecondargumentin.__init__()isknownasthename,anditwillstorethenameofthePersoninatextstring. Afterwehavedefinedtheclass,weareabletobegininvokingit.Thatis,wecanbegincreatingobjectsforthatparticularclass.Toaccomplishthis,wewillhavetouseanoldsyntax.Calltheclasswiththeparentheses(())thatusesthesamesyntaxweemploytoinvokeanyPythonfunction: #InstantiatingPerson jonny=Person("JonnyJoe") jonny.name Output: 'JonnyJoe' InPython,theclassnameisthelanguagethatotherlanguages,likeC++andJava,areknownastheconstructorforclasses.Inthesameway,aswedidinPerson,thatcausestheinstanceoftheclasscreationprocess,whichrunswithtwophases: Createanentirelynewinstanceoftheclassthatwewishtotarget. Initiatetheinstancebyusingtheappropriateinstancesattributevalues. Inthefollowingexample,thedataweinputintheformofanargumentforPersonispassedinternallythrough.__init__()andlaterisassignedtoaninstanceattribute.name.Inthisway,wecaninitializeourinstanceofourPerson,jonny,withthecorrectdata,whichwecanverifybyvisiting.name.Success!JonnyJoeis,infact,hisname. Oncetheusershavemasteredthemechanismofinitializationforobjectsandthemechanismforobjectinitialization,theyarenowreadytounderstandwhatPythondoespriortogettingtothisstageintheinstantiationprocess.It'stimetoexploreanothermethodthatisknownas.__new__().ThismethodisresponsibleforthecreationofnewinstancesinPython. The.__new__()specialmethodusestheunderlyingclassasthefirstargumentandreturnsanewobject.Theobjectisusuallyanexampleoftheclassbeinginput.However,itmaybeaninstancebelongingtoadifferentclassincertaincases. Iftheobject.__new__()returnsaninstanceoftheclasscurrentlybeingcalled,Thisinstancewillbeimmediatelytransferredonto.__init__()toinitializetheclass.Thesetwostepstakeplacewheneverweinvoketheclass. ThePythonobjectsclassisthedefaultorbaseversionfor.__new__()and.__init__().Contraryto.__init__()thereisnoneedtomodify.__new__()inourowncustomclasses.Inmostcaseswecancountonthedefaultimplementation. Tosumup,thelessonswehavelearnedsofar,thePythoninstantiationprocessbeginsbycallinganinstanceofaclassusingthecorrectarguments.Theprocessthengoesthroughtwophasescreatingobjectsusingtheuseofthe.__new__()methodandinitializationoftheobjectbyusingit's.__init__()method. OncewehavemasteredtheinternalbehaviourofPython,wearenowabletobeginprovidingseveralconstructorswithinourclasses.Thatis,wewilloffermultiplemethodstocreateobjectsinthesamePythonclass. HowtoDefineMultipleClassConstructors Sometimes,wewouldliketowriteclassesthatallowustobuildobjectsusingargumentsofvariousdatatypesorevendifferentnumbersofarguments.Onemethodistoprovidedifferentconstructorswithintheclassinquestion.Eachconstructorallowsforthecreationofinstancesbyusinganentirelydifferentsetofarguments. Certainprogramminglanguages,likeC++,C#C#,andJava,areabletosupportoverloadingmethodsorfunctions.Thisfeatureletsusoffermultipleclassconstructorssinceitallowsustowritemultiplemethodsorfunctionsthathavethesamenamebutwithdifferentimplementations. Methodoverloadingistheprocessofdecidingonthewaywecallthemethodthelanguagewillchoosethemostappropriateimplementationforrunning.Thus,ourmethodcouldaccomplishdifferenttasksdependingonthesituationoftheinstruction. Unfortunately,Pythondoesn'tsupportfunctionoverloadingdirectly.Pythonclassesstorethenamesoftheirmethodswithintheinternaldictionaryknownas.__dict__thatholdsclassnamespace.SimilartotheotherPythondictionary.__dict__can'tcontainrepeatedkeys,whichmeanswecannothavemorethanonemethodwiththesamenamewithinthesameclass.Ifwetrydoingthat,Pythonwillonlybeabletorememberthemostrecentexecutionofthatmethodinthetime: #greetr.py classGreeterr: defsay_hello(self): print("Hello,Universe") defsay_hello(self): print("Hello,Javatpoint") Forthisinstance,webuildGreeterrasthenamesuggestsinthisexample.ItisaPythonclassusingtwomethods.Bothmethodssharethesamename.However,theyuseslightdifferencesintheirimplementations. Tofindouttheconsequencesofhavingtwomethodssharethesamenameandclass,saveourclasstothegreetr.pyfileinthedirectoryweworkinandexecutethefollowingcodeduringthisactivesession: fromgreetrimportGreeterr greeter=Greeterr() greeter.say_hello() Greeterr.__dict__ Output: Hello,Javatpoint mappingproxy({'__module__':'greetr', 'say_hello':, '__dict__':, '__weakref__':, '__doc__':None}) Inthisinstance,inthisexample,weinvoke.say_hello()ongreeter.ItisaninstancebelongingtotheGreeterrclass.Weseehello,Javatpointinplaceofhello,Universeinourdisplay,andthisprovesthatthesecondversionofthemethodwinsoverthefirst. Thelastlineofcodescrutinizesthecontentsin.__dict__,uncoveringthatthenameofthemethod,say_hello,isonlyusedonceinthenamespacefortheclass.ThisisinlinewiththewaythedictionariesfunctioninPython. ThesamethinghappenswhenusingfunctionswithinthePythonmoduleandinaninteractivitysession.Theimplementationthathasthemostfunctionsthathavethesamenameissuperiortotheotherimplementations: defsay_hello(): print("Hello,Universe") defsay_hello(): print("Hello,Javatpoint") say_hello() Output: Hello,Javatpoint Twofunctionsaredefinedwiththeidenticaltitle,say_hello(),inanidenticalinterpretersession.Buttheseconddefinitionreplacesthepreviousone.Whenweinvokethefunction,wewillget"Hello,Javatpoint",anditconfirmsthefirstdefinitionistheonethatprevails. Anothermethodthatcertainprogramminglanguagesemploytooffernumerouswaystocallanoperationormethodincludesmultipledispatches. Thistechniqueallowsustocreatemultipleversionsofthesamemethodorfunctionandthendynamicallydispatchtheimplementationwewanttousebasedonthetypeorotherattributesoftheargumentsusedwithintherequest.ItispossibletouseavarietyofprogramsfromthestandardlibrarytoincorporatethistechniqueintothecodewewriteinPythoncode. Pythonisaveryversatileandfeature-richlanguage.Itoffersafewmethodstousemultipleconstructors,makingourclassesmoreadaptable. Inthenextsection,wewillbeabletosimulatemultipleconstructorsusingadditionalargumentsandexamineargumentstodeterminethevariousbehaviourinourinitializers. HowtoSimulateMultipleConstructorsinourClasses OnemethodthatisquiteusefultosimulatemultipleconstructorswithinthePythonclasswouldbetosupply.__init__()withoptionalargumentsbyusingdefaultarguments.Thisway,weareabletousetheclassconstructorinavarietyofwaysandexperiencethesamebehavioureverytime. Anotheroptionistoverifythedataformatthatwepasspassedto.__init__()toofferdifferentbehavioursbasedonthedatawepassduringthecall.Thismethodletsussimulateseveralconstructorswithinthesameclass. Thissectionwillhelpusdiscoverthefundamentalsofhowtosimulatedifferentwaystobuildobjectsbyprovidingthecorrectdefaultvaluesforargumentstothe.__init__()methodandbyexaminingthetypeofdatausedintheargumenttothemethod.Bothmethodsrequirejustonemethodof.__init__(). UseOptionalArgumentValuesin.__init__() AsimplePythonicmethodtosimulatemultipleconstructorsisimplementingthe.__init__()methodthatusesanoptionalargument.Itispossibletodothisbyspecifyingtheappropriatedefaultarguments. Tothisend,sayweneedtocodeafactoryclasscalledCumulativePowerFactory.Thisclasscreatescallableobjectsthatcalculatespecificpowersusingthestreamofnumericalvaluesastheinput.Itisalsonecessaryforourclasstokeeptrackofthetotalpoweroftheconsecutivepowers.Additionally,ourclassshouldacceptanargumentthatholdsthatthereisaninitialamountforthesumofpower. Createapowers.pyfileinthedirectorywearecurrentlyin.ThentypeinthefollowingcodetoimplementCumulativePowerFactory: #powerr.py classCumulativePowerFactory: def__init__(self,exponent=2,*,start=0): self._exponent=exponent self.total=start def__call__(self,base): power=base**self._exponent self.total+=power returnpower TheinitializerofCumulativePowerFactorytakestwooptionalarguments,exponent,andstart.Thefirstargumentcontainstheexponentwewillbeusingtocalculateasetofpowers.Thedefaultvalueis2,themostcommonlyusedvalueforcomputingpower. Thesymbolofthestarorasterisk(*)followinganexponentsignifiesthatbeginisonlyakeywordargument.Inordertopassavalueintoanargumentthatisonlyforkeywords,itisnecessarytospecifytheargument'snameinaspecific.Forexample,tochangetheargumentvaluetovalue,itisnecessarytoentertheword"arg=value"explicitly. StartArgument:Thebeginningargumentistheinitialvalueusedtocalculatethecumulativesumofpower.Thedefaultvalueiszero,whichisthebestvalueinthoseinstanceswherewedon'thaveacalculatedvaluetosetthepowersum. Thespecialmethod.__call__()turnstheinstancesofCumulativePowerFactoryintocallableobjects.Inotherwords,wecancalltheinstancesofCumulativePowerFactorylikewecallanyregularfunction. Within.__call__(),Wefirstcalculatethepowerbasethatwehaveraisedtoanexponent.Then,weapplytheresultantnumbertothevaluecurrentlyin.total.Intheend,returnthepowerwecomputed. TogiveCumulativePowerFactoryatry,openaPythoninteractivesessioninthedirectorycontainingpowerr.pyandrunthefollowingcode: frompowerrimportCumulativePowerFactory square=CumulativePowerFactory() square(26) Output: 676 Input: square(36) Output: 1296 Input: square.total Output: 1972 Input: cube=CumulativePowerFactory(exponent=3) cube(31) Output: 29791 Input: cube(36) Output: 46656 Input: cube.total Output: 76447 Input: initialized_cube=CumulativePowerFactory(3,start=2205) initialized_cube(26) Output: 17576 Input: initialized_cube(46) Output: 97336 Input: initialized_cube.total Output: 117117 TheseexamplesshowhowCumulativePowerFactorysimulatesmultipleconstructors.Forinstance,theinitialconstructordoesn'tacceptarguments.Itletsuscreateinstancesofaclassthatcomputethepowers2,whichwillbethestandardvaluefortheexponentargument.The.totalinstanceattributecontainsthepowerofthecomputingpoweraswework. Thesecondexampleillustratesanoperatorthattakestheexponentforanargument.Inthisinstance,.totalworksexactlyasitdidinthepreviousexample.Itproducesacallableinstancethatcalculatescubes. ThethirdexampleshowshowCumulativePowerFactoryseemstohaveanotherconstructorthatallowsustocreateinstancesbyprovidingtheexponentandstartingarguments.Now,.totalstartswithaninitialnumberof1972,whichistheinitialvalueforthepowerofthesum. Utilizingoptionalargumentswhenusing.__init__()inourclassesisasimplePythonicmethodofcreatingclassesthatemulatemultipleconstructors. CheckArgumentTypesin.__init__() TodeterminethenatureofavariableinPython,itiscommontouseaninbuiltisinstance()function.ThefunctionwillreturnTruewhenanobjectisanobjectofaparticularclassandFalseotherwise.Anothermethodtoemulatethemultipleconstructorsistocreatea.__init__()methodthatperformsdifferentlybasedonthetypeofargument. isinstance(46,int) Output: True Input: isinstance(42,float) Output: False Input: isinstance(47,(list,int)) Output: True Thefirstargumentfor"isinstance()"istheobjectwewanttotype-check.Anotherargumentwillbetheclassorkindofreference.Itisalsopossibletoprovideanumberofdatatypesinthiscase.IftheusersareusingPython3.10orlater,theymayalsomakeuseofthenewUnionsyntaxusingpipes(|). Then,saywewouldliketoworkincreatingourclassandthatwerequiretheclasstoacceptthedateofbirthfortheperson.Ourcodewillshowthatbirthdateinatimeobject;however,tomakethingseasierforusers,theyhavetheoptionofgivingbirthdatesinastringusinganappropriateformat.Inthisinstance,wecouldimplementsomethinglikethis: fromdatetimeimportdate classPerson: def__init__(self,name,birth_date): self.name=name ifisinstance(birth_date,date): self.birth_date=birth_date elifisinstance(birth_date,str): self.birth_date=date.fromisoformat(birth_date) jonny=Person("JonnyJoe","1993-12-19") jonny.birth_date Output: datetime.date(1993,12,19) Input: jammy=Person("JammyJoe",date(1991,7,25)) jammy.birth_date Output: datetime.date(1991,7,25) Within.__init__()itisfirstnecessarytodefinethestandard.nameattribute.Ifaclauseintheconditionalstatementdeterminesifthebirthdateisadayobject.Ifyes,thencreate.birth_datetostorethecurrentdate. Theelifclausetestswhetherwecandetermineifthebirth_dateargumentsareoneofthestringtypes.Ifyes,set.birth_datetoadateobjectderivedfromthesuppliedstring.Itisimportanttonotethatthebirth_dateargumentmustbeastringcontainingthedatewithanISOformat.SuchasYYYYY-DD-MM. That'sit!Nowwehavegota.__init__()methodthatsimulatesatypethathasmultipleconstructors.Oneconstructoracceptsanargumentofthedatetype.Theotherconstructoracceptsargumentsoftypestring. Theapproachusedintheaboveillustrationhasthedisadvantagethatitisn'tscalable.Ifweareusingseveralargumentsthatmaybeusedtorepresentvarioustypesofdata,ourapplicationcouldquicklybecomeanissue.Therefore,thisapproachisregardedasananti-patternwithinPython. Forinstance,whatwouldoccurifouruserenteredthedateandtimeamountforabirthdate?Takealookatthefollowingcodesnippet. lucky=Person("LuckySam",1033222000) lucky.birth_date Output: --------------------------------------------------------------------------- AttributeErrorTraceback(mostrecentcalllast) in 1lucky=Person("LuckySam",1033222000) 2 ---->3lucky.birth_date AttributeError:'Person'objecthasnoattribute'birth_date' Ifweattempttoconnectto.birth_date,wereceivetheerrormessageindicatingthattheattributeisunavailablebecauseourconditionalstatementdoesnothavebranchesthatconsideranalternativeformatfordates. Toresolvethisproblem,continuetoaddtheelifclausestoincludeallpossibleformatsfordatesthatuserscanuse.Itisalsopossibletoincludeanotheralternativeclausetodetectnotsupporteddateformats: fromdatetimeimportdate classPerson: def__init__(self,name,birth_date): self.name=name ifisinstance(birth_date,date): self.birth_date=birth_date elifisinstance(birth_date,str): self.birth_date=date.fromisoformat(birth_date) else: raiseValueError(f"unsupporteddateformat:{birth_date}") lucky=Person("LuckySam",1033222000) Output: --------------------------------------------------------------------------- ValueErrorTraceback(mostrecentcalllast) in 12 13 --->14lucky=Person("LuckySam",1033222000) in__init__(self,name,birth_date) 9self.birth_date=date.fromisoformat(birth_date) 10else: --->11raiseValueError(f"unsupporteddateformat:{birth_date}") 12 13 ValueError:unsupporteddateformat:1033222000 Inthiscase,itistheotherwiseclause.Itisexecutedifthenumberinbirthday_dateisn'tanactualdayobjectorstringthatcontainsalegitimateISOdate.Thisway,theuniquescenariodoesnothappeninsilence. HowtoProvideMultipleConstructorsWith@classmethodinPython AneffectivemethodtoprovideseveralPythonconstructorsisutilizingthe@classmethoddecorator.ThisdecoratorletsusconvertanormalmethodintoanactualClassMethod. Asopposedtothenormalmethod,theclassdoesnotmakeuseofthisinstanceselfasanargument.Instead,theyconsideranentireclass,typicallyincludedintheCLSargument.Utilizingthewordclstoidentifytheargumenthasbecomeawell-knownpracticewithinthePythoncommunity. Thisisthepreliminarysyntaxusedtodefineclasses: classDemo_Class: @classmethod defclass_method(cls): print(f"Thisisaclassmethodfrom{cls.__name__}!") Demo_Class.class_method() Output: ThisisaclassmethodfromDemo_Class! Input: demo=Demo_Class() demo.class_method() Output: ThisisaclassmethodfromDemo_Class! Democlassistheclassmethodthatusesthebuilt-in@classmethoddecorator.Thefirstargumentin.class_method()istheclass'sname.Withthisargument,weareabletoaccesstheclassinsidetheclassitself.Inthisinstance,wewillneedtohaveaccesstousingthe.__name__attribute,whichrecordsinformationabouttheclassinatextstring. It'simportanttoknowthatwecaninvoketheclassmethodbyusingtheclassoraspecificexampleofthatclassinquestion.Theprimaryreasonforusingclassesasconstructorsfortheclassmethodisthatwedon'trequireaninstancetoinvokeaninstanceofaclassmethod.However,wecall.class_method(),wewillgetDemo_Classforthefirstargument. Theuseof@classmethodallowsustoincludethenumberofexplicitconstructorswerequireforaparticularclass.It'saPythonicandwell-knownmethodtousemultipleconstructors.ItisalsopossibletocallthiskindofconstructoranalternativeconstructorinPython,suchasRaymondHettingerusesinhisPyConpresentationThePythonClassDevelopmentToolkit. WhatcanwedonowtouseaclassmethodtoaltertheinstantiationprocessofPython?Insteadoftweaking.__init__()andtheinitializationoftheobject,itispossibletocontrolbothofthestages:thecreationofobjectsandinitialization.Inthefollowingexample,wewillbetaughthowtoaccomplishthis. ConstructaCirclefromItsDiameter Forourfirstclassconstructor,using@classmethod,Let'ssayweareprogrammingforageometric-relatedprogramandrequirethecircleclass.Atfirst,wewilldefineourclassinthefollowingmanner: #circle1.py importmathasm classCircle: def__init__(self,radius): self.radius=radius defarea(self): returnm.pi*self.radius**2 defperimeter(self): return2*m.pi*self.radius def__repr__(self): returnf"{self.__class__.__name__}(radius={self.radius})" TheclassimplementsmethodstocalculatetheperimeterandareaoftheCirclewiththePythonmathematicalmodule.Intheinitializer,Circleusesaradiusnumberintheformofanargumentandthenstoresthatasanattributeintheinstancecalled.radius.Theprocedure.__repr__()providestheappropriateexpressionofastringthatisappropriatefortheclass. Createcircle1.pyfileinthedirectoryweworkin.Afterthat,openPythoninterpreterandrunthefollowingprogramtotestCircle: fromcircle1importCircle circle=Circle(52) circle Output: Circle(radius=52) Input: circle.area() Output: 8494.8665353068 Input: circle.perimeter() Output: 326.7256359733385 Cool!Ourclassisfunctioningproperly!Nowimaginethatwewouldliketocreateacircleusingthediameter.It'spossibletodothisusingCircle(diameter+2.),butthat'snotexactlyPythonicaswellasintuitive.It'sbesttouseanalternativeconstructorthatcancreatecirclessimplybyusingthediameteroftheCircledirectly. AddthefollowingclassmethodtotheCirclejustinthemiddle.__init__(): #circle.py importmathasm classCircle: def__init__(self,radius): self.radius=radius defarea(self): returnm.pi*self.radius**2 defperimeter(self): return2*m.pi*self.radius def__repr__(self): returnf"{self.__class__.__name__}(radius={self.radius})" @classmethod deffrom_diameter(cls,diameter): returncls(radius=diameter/2) Inthiscase,thecodedefines.from_diameter()asanexampleofaclassmethod.Themethod'sfirstargumentwillbeanidtotheclassthatitisapartofClasscalledCircle. ThesecondargumentisthesizeoftheCirclewewishtomake.Intheprocess,wefirstdeterminetheradiusbyusingtheinputvalueinthediameter.Then,wecreateacirclebycallingCLSusingtheradiuscalculatedusingthediameterargument. Inthismanner,weareincompletecontrolofdefiningandinitializingallinstancesforCirclewiththediameterusedintheargument. ThefunctionthatcallstheclsargumentrunstheinitializationandcreationproceduresthatPythonrequirestocreatetheclass.Then,.from_diameter()returnsthenewlycreatedinstancetotheuser. Here'showtousethebrand-newconstructorthatwehavecreatedtocreatecirclesmakinguseoftheradius: fromcircleimportCircle Circle.from_diameter(84) Output: Circle(radius=42.0) Input: circle.area() Output: 5541.769440932395 Input: circle.perimeter() Output: 263.89378290154264 Themethodof.from_diameter()onCircleproducesafreshbrandinstanceofthisclass.Creatingthatinstanceutilizesanactualdiameter,nottheradius.TheremainderofthefunctionpartofCircleisthesamewayitwasbefore. The@classmethod,similartotheaboveexample,isthemostcommonlyusedmethodtospecifymultipleconstructorsforourclasses.Thisway,weareabletochoosetheappropriatenameforeachconstructorthatofferandcanhelpmakeusinmakingourcodemoreunderstandableandmanageable. BuildaPolarPointfromCartesianCoordinates Foramoredetailedexampleofimplementingmultipleconstructorswithclassmethods,supposethatwehavegotaclassrepresentingthepolarspotconceptinourmath-relatedprogram.ItisnecessarytoallowourclasstobemoreflexiblesothatwecanbuildnewinstanceswithCartesiancoordinatesinaddition. Here'showwecancreateaconstructortosatisfythisneed: #pointt.py importmathasm classPolarPoint: def__init__(self,distance,angle): self.distance=distance self.angle=angle @classmethod deffrom_cartesian(cls,x,y): distance=m.dist((0,0),(x,y)) angle=m.degrees(m.atan2(y,x)) returncls(distance,angle) def__repr__(self): return( f"{self.__class__.__name__}" f"(distance={self.distance:.1f},angle={self.angle:.1f})" ) Inthisinstance,.from_cartesian()acceptstwoargumentsthatrepresentthearea'scoordinates:xaswellastheCartesiancoordinates.ThemethodthencalculatestheneededdistanceandangletocreatetheappropriatePolarPointobjects.Then,.from_cartesian()producesanewlycreatedinstancefortheclass. Here'showtheclassfunctionsbyusingthetwocoordinatesystems. frompointtimportPolarPoint #Withpolarcoordinates PolarPoint(16,21.6) Output: PolarPoint(distance=16.0,angle=21.6) Input: #Withcartesiancoordinates PolarPoint.from_cartesian(x=22,y=15) Output: PolarPoint(distance=26.6,angle=34.3) Intheseinstances,wewillemploythestandardinstantiationmethodandouralternateconstructor.from_cartesian(),whichallowsustogeneratePolarPointinstancesthatuseconceptuallydistinctinitializationarguments. ExploreMultipleConstructorsinExistingPythonClasses Utilizingthe@classmethoddecoratortoofferseveralconstructorsfortheclassisacommonpracticeinPython.Therearenumerousexamplesofthestandardandbuilt-inclassesthatmakeuseofthismethodtooffermultipledifferentconstructors. Withinthisarticle,wewillbeabletolearndetailsabout3oftherenownedcasesofthisclass:dict,datetime.dateandpathlib.Path. ConstructDictionariesfromKeys DictionariesarethemostfundamentalkindofdatainPython.TheyarepresentineverypartofPythoncode,whetherdirectlyorindirectly.They'realsoanintegralpartofthelanguagesincesignificantpartsthatcomprisePython'sCPythonapplicationdependonthem. TherearemanymethodsofidentifyingdictionaryinstancesinPython.Dictionaryliteralscanbeusedthatarekey-valuepairsthatarecurlybracketed({}).Itisalsopossibletocall"dict()"explicitlywithkeywordargumentsorthesequenceoftupleswithtwoitems,asanexample. Thiswell-knownclassalsoprovidesanalternativeconstructor,called.fromkeys().Thisclassmethodusestheformofanarrayofkeysaswellastheoptionofanumberofkeysandanoptionalvalue.Thevalueargumentisoptional.ValueisdefaultedtoNone,andisitisthesamevalueasallkeysoftheresultingdictionary. Whatdotheusersthink.fromkeys()helpthemintheirprogram?Iftheymanageananimalsanctuaryandlooktodevelopanappthatwilltrackthenumberofanimalscurrentlyattheirshelter.Theapplicationmakesuseofanalphabeticaldictionarytorecordtheanimal'sinventory. Becausetheuserknowwhatspeciesofanimaltheycanaccommodateintheirshelter,theycanbuildtheinventorydictionaryfromscratch,suchasinthefollowingcodeexample: allowed_animals=["Tiger","lion","Cobra","donkey"] animal_inventory=dict.fromkeys(allowed_animals,0) animal_inventory Output: {'Tiger':0,'lion':0,'Cobra':0,'donkey':0} Inthisinstance,wehaveconstructedaninitialdictionarybyusing.fromkeys()thattakeskeysfromanimalsthatareallowedtobeinthesystem.Theinventorywecreatethateachanimalhastozerobysupplyingthisnumberforthesecondargumentin.fromkeys(). Aswehavealreadylearned,valuedefaultstoNone,whichisanappropriatefirstvalueforthekeysofourdictionaryincertainsituations.Intheinstancebelow,zeroisanidealvalueaswearedealingwiththenumberofindividualsareineachspecies. Theothermappingswithinthestandardlibraryhaveaconstructornamed.fromkeys().ThisistrueforOrderedDictaswellasdefaultdictandUserDict.ForinstanceUserDict'ssoftwaresourceforUserDictoffersthisimplementation.fromkeys(). @classmethod deffromkeys(cls,iterable,value=None): d=cls() forkeyiniterable: d[key]=value returnd Thisisbecause.fromkeys()usesfromaniterableandtheamountintheformofarguments.Themethodcreatesabrand-newdictionaryusingtheclsmethod.Then,itloopsoverthekeyswithinaniterativeandassignseachvaluetoavaluesetatNoneinthenormalway.Intheend,themethodreturnsthenewlycreateddictionary. Createdatetime.dateObjects Itisthedatetime.dateclassfromthestandardlibraryisanotherclassthatutilizesnumerousconstructors.Thisclasshasanumberofalternativestoconstructors,including.today(),.fromtimestamp(),.fromordinal()and.fromisoformat().Allofthempermitustocreatedatetime.dateobjectsusingthesameargumentsbutwithdifferentconcepts. Herearesomeexamplesofhowwecanusetheconstructorsmentionedabovetoconstructdatetime.dateobjects: fromdatetimeimportdate fromtimeimporttime #Standardconstructor date(2021,12,23) Output: datetime.date(2021,12,23) Input: date.today() Output: datetime.date(2021,12,23) Input: date.fromtimestamp(1632520000) Output: datetime.date(2021,9,25) Input: date.fromtimestamp(time()) Output: datetime.date(2022,3,16) Input: date.fromordinal(738128) Output: datetime.date(2021,12,4) Input: date.fromisoformat("2021-12-23") Output: datetime.date(2021,12,23) Thefirstexampleemploysthestandardconstructorofclassesasthereference.Thesecondexampledemonstrateshowtoutilize.today()toconstructatimeobjectbasedonthecurrentday'sdate. Theremainingexamplesdemonstratethewaydatetime.dateusesseveralclassestooffermultipleconstructors.Thevarietyofconstructorsavailableallowstheinstantiationproceduretoberobustandflexibleandcoversavarietyofscenarios.Thisalsoenhancestheaccessibilityofourcodebyprovidingexplicitmethodnames. FindOurPathtoHome ThePythonpathlibmodulethatispartofthestandardlibraryoffersmodernandefficienttoolsforefficientlyhandlingthesystempathinyourprogram.Iftheuserhaveneverheardofthismodulebefore,theyshouldgothroughPython3'spathlibmodule:TheArtofTamingtheFileSystem. ThemostefficienttoolavailableinthepathliblibrarycanbefoundinthePathclass.Thisclassletsusmanageoursystem'sPathonacross-platformbasis.ThePathisadifferentstandardlibraryclassthathasseveralconstructors.Forinstance,wewillcomeacrossPath.home(),whichcreatesanobjectcalledapathfromourhomedirectory frompathlibimportPath Path.home() Output: WindowsPath('C:/Users/UserName') The.home()constructorproducesabrandnewpathobjectwhichrepresentsouruser'shomedirectory.ThisalternativeconstructorcouldbebeneficialwhendealingwithsettingsfileswithinourPythonapplicationsandproject. Conclusion WritingPythonclassesthathaveseveralconstructorswillhelpourcodebecomemoreflexibleandadaptable,allowingformanydifferentusescenarios.Multipleconstructorsareaneffectivefeaturethatletsuscreateinstancesofthecoreclasswithargumentsofdifferentkinds,differentnumbersofarguments,orboth,dependingontheneedsofourusers. Inthiscourse,wehavelearnedhowtodo: Simulatemultipleconstructorsbyusingadditionalargumentargumentsalongwithtypechecking. Createmultipleconstructorswiththeinbuilt@classmethoddecorator NextTopicProfilingthePythoncode ←prev next→ ForVideosJoinOurYoutubeChannel:JoinNow Feedback SendyourFeedbackto[email protected] HelpOthers,PleaseShare LearnLatestTutorials Splunk SPSS Swagger Transact-SQL Tumblr ReactJS Regex ReinforcementLearning RProgramming RxJS ReactNative PythonDesignPatterns PythonPillow PythonTurtle Keras Preparation Aptitude Reasoning VerbalAbility InterviewQuestions CompanyQuestions TrendingTechnologies ArtificialIntelligence AWS Selenium CloudComputing Hadoop ReactJS DataScience Angular7 Blockchain Git MachineLearning DevOps B.Tech/MCA DBMS DataStructures DAA OperatingSystem ComputerNetwork CompilerDesign ComputerOrganization DiscreteMathematics EthicalHacking ComputerGraphics SoftwareEngineering WebTechnology CyberSecurity Automata CProgramming C++ Java .Net Python Programs ControlSystem DataMining DataWarehouse JavatpointServicesJavaTpointofferstoomanyhighqualityservices.Mailuson[email protected],togetmoreinformationaboutgivenservices.WebsiteDesigningWebsiteDevelopmentJavaDevelopmentPHPDevelopmentWordPressGraphicDesigningLogoDigitalMarketingOnPageandOffPageSEOPPCContentDevelopmentCorporateTrainingClassroomandOnlineTrainingDataEntryTrainingForCollegeCampusJavaTpointofferscollegecampustrainingonCoreJava,AdvanceJava,.Net,Android,Hadoop,PHP,WebTechnologyandPython.Pleasemailyourrequirementat[email protected]Duration:1weekto2weekLike/Subscribeusforlatestupdatesornewsletter
延伸文章資訊
- 1Python Class Constructor - Python __init__() Function
Python doesn't support multiple constructors, unlike other popular object-oriented programming la...
- 2What is a clean, Pythonic way to have multiple constructors in ...
Python does not support explicit multiple constructors, yet there are some ... If multiple __init...
- 3What is a clean "pythonic" way to implement multiple ...
As far as I know, you can't have multiple __init__ functions in a Python class. So how do I solve...
- 4Is it possible to define multiple constructors in Python?
- 5Providing Multiple Constructors in Your Python Classes
Note: The .__new__() special method is often called a class constructor in Python. However, its j...