Python - Class Constructor __init__ method - DYclassroom
文章推薦指數: 80 %
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.
延伸文章資訊
- 1__init__ in Python - GeeksforGeeks
The Default __init__ Constructor in C++ and Java. Constructors are used to initializing the objec...
- 2__init__ in python - Javatpoint
__init__ in python with Python with python, tutorial, tkinter, button, overview, canvas, frame, e...
- 3Python 入門指南- 單元11 - __init__() 方法 - 程式語言教學誌
本篇文章介紹Python 類別中的__init__() 方法, __init__() 方法的主要功能為初始化實體屬性。 ... class Demo: def __init__(self, v1...
- 4Python __init__
In this tutorial, you'll learn how to use the Python __init__() method to initialize objects.
- 5Python __init__() Function - W3Schools
Note: The __init__() function is called automatically every time the class is being used to creat...