← Back to Python Course | Chapter 7: OOP | Lesson 3 of 11

Python Constructors

What is a Constructor?

A constructor is the method Python calls automatically the moment an object is created, and in Python that's __init__ -- despite the name, it doesn't allocate the object (that's __new__ behind the scenes), it just initializes the attributes on the object that already exists.

Example: What is a Constructor?

python
class Dog:
    def __init__(self):
        print("A new dog is created")

Dog()

Default Constructor

A constructor that only takes self and no other parameters gives every new object the exact same starting values, which is fine for simple cases but means you can't customize an object at creation time -- every Dog() would start with an identical name, for instance.

Example: Default Constructor

python
class Dog:
    def __init__(self):
        self.name = "Unnamed"

d = Dog()
print(d.name)

Parameterized Constructor

Accepting extra parameters beyond self (def __init__(self, name, breed):) lets each call to the class supply its own values, so Dog(Rex, Labrador) and Dog(Milo, Poodle) end up as genuinely different objects from the same blueprint.

Example: Parameterized Constructor

python
class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

rex = Dog("Rex", "Labrador")
print(rex.name, rex.breed)

Default Parameter Values

Giving a constructor parameter a default value (def __init__(self, name=Unnamed):) makes that argument optional -- callers who don't pass a name get the fallback, while callers who do pass one override it, without needing two separate constructors.

Example: Default Parameter Values

python
class Dog:
    def __init__(self, name="Unnamed"):
        self.name = name

print(Dog().name)
print(Dog("Rex").name)

The Role of self

self refers to the specific object being built or acted on right now, which is why 'self.name = name' inside __init__ stores the passed-in value onto that particular instance rather than some shared or global variable -- every method needs self to know which object it's operating on.

Example: The Role of self

python
class Dog:
    def __init__(self, name):
        self.name = name

d = Dog("Rex")
print(d.name)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.