0
0
PythonHow-ToBeginner · 3 min read

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 self as the first parameter.
  • Not assigning parameters to self attributes, 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:

ConceptDescription
__init__ methodSpecial method called when creating an object
self parameterRefers to the current object instance
Attribute assignmentUse self.attribute = value to store data
Constructor nameMust be exactly __init__ with double underscores
Multiple parametersYou 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.