Python Constructors
In this page:
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?
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
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
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
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
class Dog:
def __init__(self, name):
self.name = name
d = Dog("Rex")
print(d.name)
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: