In Python, the constructor is a special method called __init__. It runs automatically when you create an object from a
class.
This page covers Constructor in Python. For a language-agnostic introduction, see Constructor.
Defining __init__#
Like all instance methods in Python, __init__ takes self as its first parameter. Additional parameters receive the values passed when creating the object.
class Player:
def __init__(self, name):
self.name = nameself.name = name stores the argument on the object.
Creating an Object#
Pass arguments directly when calling the class. Python calls __init__ automatically.
player = Player("Alice")
print(player.name) # AliceDefault Values#
Parameters can have default values, making them optional.
class Player:
def __init__(self, name="Player"):
self.name = name
player = Player()
print(player.name) # PlayerCommon Mistakes#
Forgetting self as the first parameter
__init__ must have self as its first parameter. Omitting it causes a TypeError when creating an object: __init__() takes 1 positional argument but 2 were given.
Not storing the argument with self
Writing name = name inside __init__ creates a local variable that disappears immediately. Use self.name = name to attach the value to the object.
Misspelling __init__
Python won’t raise an error if you write __Init__ or _init_ — it just won’t be called as a constructor. The name must be exactly __init__ with two underscores on each side.
Calling __init__ directly
You don’t call player.__init__("Alice") after the object exists — the constructor runs once automatically when you write Player("Alice"). Calling it again is possible but almost never correct.
Resources#
- Classes — Python documentation (external link) — Python.org
- Constructor (object-oriented programming) (external link) — Wikipedia