Python - Class Constructor __init__ method - DYclassroom

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

In this tutorial we will learn about the class __init__ method in Python. We learned about classes and how to create objects using classes in the Python ... : Home SignUp LogIn Tutorial InterviewQuestions App MCQ Games Project Reference Howto AllContent Aptitude Conversion BooleanAlgebra Flowchart IPAddress LogicGates PseudoCode Algorithm BacktrackingAlgorithm DynamicProgramming Graph GreedyAlgorithm RecursionAlgorithm SearchingAlgorithm SearchingPattern SortingAlgorithm WebDev Bootstrap Babel Bower ChartJS CodeMirror CSS ES6 Grunt HTML JavaScript jQuery JWT TinyMCE TypeScript ProgrammingLanguage CProgramming Java PHP Python VersionControl Git Database MongoDB MySQL PostgreSQL Unix/Linux UnixShellProgramming Vim Testing Mocha MochaChai PHPUnit Code Programming JavaScriptCode Design DesignPatterns Sketch Photoshop More... ApacheActiveMQ DSLR Money WebDev CSS HTML JavaScript jQuery Database DBMS Redis SQL ProgrammingLanguage CProgramming PHP ASCIICharacters Database GreekLetters HTMLEntities JavaScript Linux MathSymbols RomanNumerals Server Web YouTube More... Mac Ubuntu VMware Website WordPress Web BootstrapEditor ColorMixer CSSMinifier HTMLEditor HTMLEntitiesEncoderDecoder IPAddress JavaScriptMinifier URLEncoderDecoder Util DayoftheDate FindFileinfo ImagetoBase64 RandomPasswordGenerator Calculator CompoundInterestCalculator EMICalculator FD-FixedDepositCalculator RD-RecurringDepositCalculator SimpleInterestCalculator AptitudeQuestions CountryCapital GeneralEnglish MockTest Multiply PicturePuzzle PlusMinus SliderPuzzle Sudoku TicTacToe C#Project JavaImageProcessingProject LaravelProject WebProject OpenSourceProjects dyCalendarJS dyClockJS dyScrollUpJS dyCodeHighlighter dyreimage-php GettingStarted Python-Introduction Python-HelloWorldProgram Python-Syntax Python-DataTypes Python-Variables Operators Python-ArithmeticOperators Python-RelationalOperators Python-LogicalOperators Python-AssignmentOperators Python-BitwiseOperators Python-MembershipOperators Python-IdentityOperators Python-IncrementandDecrementOperators Conditions Python-IfElsestatement Loop Python-WhileLoop Python-ForLoop Numbers Python-Numbers Python-NumberConversion Strings Python-Strings Python-StringOperators Python-StringFormatting Python-StringMethods Python-StringFormatMethod List Python-List Python-ListMethods Tuple Python-Tuple Set Python-Set Python-SetMethods Dictionary Python-Dictionary Python-DictionaryMethods Functions Python-Functions Python-Functions-Variablelengtharguments Python-LambdaFunction ScopeofVariables Python-ScopeofVariables Modules Python-Modules Python-MathModule Python-JSONModule Python-datetimeModule Python-timeModule I/O Python-Readinputfromkeyboard File Python-FileHandling ExceptionHandling Python-ExceptionHandling OOP Python-ClassesandObjects Python-ClassConstructor__init__method Python-ClassDestructor__del__method Python-Built-inClassAttributes Python-Inheritance Python-MethodOverriding Python-MethodOverloading PackageManagement Python-PIP Python-MySQL Python-MySQL-GettingStarted Python-MySQL-Insertdata Python-MySQL-Selectdata Python-MySQL-Updatedata Python-MySQL-Deletedata Python-CSV Python-ReaddatafromCSVfile Python-WritedatainCSVfile Python-ClassConstructor__init__method Python Share ←Prev Next→ Inthistutorialwewilllearnabouttheclass__init__methodinPython. WelearnedaboutclassesandhowtocreateobjectsusingclassesinthePython-ClassesandObjectstutorial.Feelfreetocheckthatout. The__init__method The__init__methodisaspecialmethodofaclass. Itisalsocalledtheconstructormethodanditiscalledwhenwecreate(instantiate)anobjectoftheclass. Weusethe__init__methodtoinitialiseclassattributesorcallclassmethods. InthefollowingPythonprogramwearecreatingthe__init__methodinsidetheAwesomeclass. #class classAwesome: #theinitmethod def__init__(self): print("Hellofromthe__init__method.") #objectoftheclass obj=Awesome() Theabovecodewillprintthefollowingoutput. Hellofromthe__init__method. Wegettheaboveoutputbecauseassoonaswecreateanobjectoftheclassthe__init__methodisautomaticallycalled. Pointstonote! Thefirstparameterofthe__init__methodisalwaysself. Theselfreferstotheobjectoftheclassandweuseittoaccessmethodsandclassattributesfrominsidetheclass. Passingargumenttothe__init__method Likeanyothermethodsofaclasswecanalsopassargumentstothe__init__method. InthefollowingPythonprogramwearepassingastringvaluetothe__init__methodatthetimeofcreatinganobject. #class classAwesome: #theinitmethod def__init__(self,name): print("Hellofromthe__init__method.") print("Name:",name) #objectoftheclass obj=Awesome("YusufShakeel") Theabovecodewillgiveusthefollowingoutput. Hellofromthe__init__method. Name:YusufShakeel Callingothermethodsfromthe__init__method Wecancallothermethodsoftheclassfromthe__init__methodbyusingtheselfkeyword. #class classAwesome: #theinitmethod def__init__(self): print("Hellofromthe__init__method.") #callingtheclassmethod self.greetings() #methods defgreetings(self): print("Hellofromthegreetings()method.") #objectoftheclass obj=Awesome() Theabovecodewillprintthefollowingoutput. Hellofromthe__init__method. Hellofromthegreetings()method. Initialiseclasspropertiesinsidethe__init__method Wecancreateclasspropertiesthatarespecifictotheclassobjectsandinitialisetheminsidethe__init__method. InthefollowingPythonprogramwearecreatingAwesomeclassandinitialisingclasspropertynameinsidethe__init__method. #class classAwesome: #classattributecommontoallobjects commonAttr="CommonAttribute" #theinitmethod def__init__(self,name): #classattributefortheobjects self.name=name #methods defgreetings(self): print("Hello%s!"%self.name) #objectoftheclass obj1=Awesome("Tom") obj2=Awesome("Jerry") #output print("Thecommonclassattribute:") print("obj1.commonAttr:",obj1.commonAttr) print("obj2.commonAttr:",obj2.commonAttr) print("Classattributespecifictoobject:") print("obj1.greetings():") obj1.greetings() print("obj2.greetings():") obj2.greetings() Theabovecodewillprintthefollowingoutput. Thecommonclassattribute: obj1.commonAttr:CommonAttribute obj2.commonAttr:CommonAttribute Classattributespecifictoobject: obj1.greetings(): HelloTom! obj2.greetings(): HelloJerry! ←Prev Next→ Share RecentlyUpdated Maximumsubarrayproblem-Kadane'sAlgorithmProgramming MaximumsubarrayproblemProgramming FindmedianofanarrayProgramming FindtheminimumandmaximumnumberinanarrayusingTournamentMethodProgramming FindtheminimumandmaximumnumberinanarrayProgramming ReverseastringProgramming DesignPatterns-StrategyPatternDesignPatterns PostgreSQL-SELECTFROMTablePostgreSQL PostgreSQL-INSERTINTOTablePostgreSQL PostgreSQL-CREATETablePostgreSQL HOME ABOUT CONTACT PRIVACY TERMS STATS SITEMAP BUG Havefunlearning:-) Copyright©2014-2022DYclassroom.Allrightsreserved.



請為這篇文章評分?