
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How does constructor method __init__ work in Python?
__init__
"__init__" is a reserved method in python classes. It is known as a constructor in OOP concepts. This method called when an object is created from the class and it allows the class to initialize the attributes of a class.
How can we use "__init__ " ?
Let's consider that we are creating a class named Car. Car can have attributes like "color", "model", "speed" etc. and methods like "start", "accelarate", "change_ gear" and so on.
Example
class Car(object): def __init__(self, model, color, speed): self.color = color self.speed = speed self.model = model def start(self): print("started") def accelerate(self): print("accelerating...") def change_gear(self, gear_type): print("gear changed")
So we have used the constructor __init__ method to initialize the class attributes.
- Related Articles
- How does Python dictionary keys() Method work?
- How does the destructor method __del__() work in Python?
- __init__ in Python
- How does jQuery.clone() method work in jQuery?
- How does jQuery.filter() method work in jQuery?
- How does jQuery.find() method work in jQuery?
- How does jQuery.eq() method work in jQuery?
- How does jQuery.map() method work in jQuery?
- How does jQuery.slice() method work in jQuery?
- How does jQuery.nextAll() method work in jQuery?
- How does jQuery replaceWith() method work?
- How does the series.copy() method work in Pandas?
- How does the series.corr() method work in pandas?
- How does the series.cummax() method work in Pandas?
- How does the series.cumprod() method work in Pandas?

Advertisements