Python Constructors
In this page:
class ClassName:
def __init__(self, parameter):
self.attribute = parameter
object_name = ClassName(argument)
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): # __init__ runs automatically when a Dog is created
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" # every Dog starts with the same fixed name
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): # extra parameters let each call customize the object
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"): # default makes the name argument optional
self.name = name
print(Dog().name) # uses the default
print(Dog("Rex").name) # overrides the default
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 # self refers to this specific Dog being created
d = Dog("Rex")
print(d.name)
- Misspelling the constructor as
__innit__or_init_, so it never runs and the object has no attributes. - Forgetting to write
self.when storing values, as inname = name, which only sets a local variable and leaves the object empty. - Returning a value from
__init__, such asreturn self, which raisesTypeErrorbecause it must returnNone.
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: