How to Create Class Constructor in Python: Simple Guide
In Python, you create a class constructor by defining the
__init__ method inside your class. This method runs automatically when you create an object and is used to initialize the object's attributes.Syntax
The constructor in Python is a special method named __init__. It always takes self as the first parameter, which refers to the object being created. You can add other parameters to pass values when creating the object.
- self: Refers to the current object.
- other parameters: Used to initialize object attributes.
python
class ClassName: def __init__(self, param1, param2): self.param1 = param1 self.param2 = param2
Example
This example shows a Person class with a constructor that sets the name and age when creating a new person object.
python
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, my name is {self.name} and I am {self.age} years old.") person1 = Person("Alice", 30) person1.greet()
Output
Hello, my name is Alice and I am 30 years old.
Common Pitfalls
Common mistakes when creating constructors include:
- Forgetting to use
selfas the first parameter. - Not assigning parameters to
selfattributes, so values are lost. - Trying to name the constructor something other than
__init__.
Here is an example of a wrong and right constructor:
python
class Wrong: def init(self, value): # Missing double underscores self.value = value class Right: def __init__(self, value): self.value = value
Quick Reference
Remember these key points about Python constructors:
| Concept | Description |
|---|---|
| __init__ method | Special method called when creating an object |
| self parameter | Refers to the current object instance |
| Attribute assignment | Use self.attribute = value to store data |
| Constructor name | Must be exactly __init__ with double underscores |
| Multiple parameters | You can add as many as needed after self |
Key Takeaways
Use the __init__ method to create a constructor in Python classes.
Always include self as the first parameter in the constructor.
Assign parameters to self attributes to store object data.
The constructor name must be exactly __init__ with double underscores.
Common errors include missing self or wrong constructor name.