Python Constructors & selfGet Certified
What Are Constructors and self in Python?
A constructor is the special method that sets up a brand new object the moment it is created. In Python the constructor is named __init__, and it runs automatically every time you call the class, as in Pet("Buddy", "golden retriever"). Its job is to give the new object its starting data, so that it never exists in a half-finished state.
The word self appears as the first parameter of __init__ and of every other method. It stands for the object that the method is working on right now. When you write self.name = name, you are saying “store this value on this object”. Understanding these two ideas, the constructor and self, makes the rest of object-oriented Python much easier to follow.
- Constructor: the
__init__method, called automatically when an object is created. - self: the object being created or used. Python passes it in for you, so you never type it in a call.
- self.attribute: a variable stored on the object that lives as long as the object does.
- Parameter vs attribute:
nameis a temporary parameter, andself.nameis the permanent attribute. - Default values: parameters such as
size="Medium"make constructor arguments optional. - No return value:
__init__must returnNone, so it never usesreturn value. - Alternative constructors: a
@classmethodcan create objects from a different kind of input.
The __init__ Constructor
When you call a class, Python first creates an empty object and then runs __init__ on it, passing the new object as self followed by the arguments you wrote. Inside the method, each line such as self.kind = kind attaches a piece of data to the object. After __init__ finishes, the finished object is returned to you.
Every object made from the same class goes through the same setup, but with different values, so each one ends up with its own separate data. Because the other methods receive the same self, they can read the attributes that the constructor stored. The example below shows two pets that share the same code but keep different names.
Try It: Introduce Two Pets
Click Test My Code to run the program. Then add a third pet with your own name and kind.
Pet class whose constructor stores a name and a kind, adds a describe() method that uses those attributes, and creates two pets whose data is kept separately.class Pet:
def __init__(self, name, kind):
self.name = name
self.kind = kind
def describe(self):
return self.name + " is a " + self.kind
buddy = Pet("Buddy", "golden retriever")
luna = Pet("Luna", "tabby cat")
print(buddy.describe())
print(luna.describe())Pet is the blueprint for every pet object.__init__ runs automatically each time a Pet is created. self is the new object, and name and kind receive the values from the call.self.name = name copies the parameter into an attribute of the object, so the value is not lost when the constructor ends.describe also receives self, which gives it access to the object’s attributes.__init__ with self, "Buddy", and "golden retriever".self is buddy. The output is Buddy is a golden retriever.self is luna. The output is Luna is a tabby cat.What self Really Is
The name self is not a Python keyword. It is only a strong convention for the first parameter of a method. When you write clicks.hit(), Python quietly translates it into Counter.hit(clicks), passing the object clicks as the first argument. Inside the method, self is simply another name for that same object.
That is why a method can read and change the attributes of the object it was called on, and why two objects never interfere with each other: each call receives a different self. A method can even return self, which hands the same object back to the caller. The example below proves that self and the object are one and the same.
Try It: Prove That self Is the Object
Click Test My Code. Then call clicks.hit() a few more times and predict the count first.
self gives back the very same object, calls the method in its long form with the object as an argument, and shows that a second counter has its own count.class Counter:
def __init__(self):
self.count = 0
def hit(self):
self.count = self.count + 1
return self
clicks = Counter()
print(clicks.hit() is clicks)
Counter.hit(clicks)
print(clicks.count)
other = Counter()
print(other.count)Counter counts how many times something happens.self, so a counter is created with Counter().count of 0.hit records one click on the object it is called on.self.count is increased by one. Only this object’s count changes.clicks.clicks. The output is True.Counter.hit(clicks) does exactly what clicks.hit() does, with the object passed in by hand. The count becomes 2.2.count attribute.0.Default Values and Keyword Arguments
Constructor parameters can have default values, just like the parameters of any function. A parameter with a default becomes optional, so callers can leave it out when the usual value is fine. Parameters without defaults must come first, and the optional ones follow them.
When a constructor has several optional parameters, keyword arguments let you choose which ones to set, no matter what order they appear in. Writing Order("tea", quantity=3) sets only the quantity and leaves the size at its default. This makes constructors flexible without needing several different versions of the class.
Try It: Orders at a Seattle Coffee Shop
Click Test My Code. Then place an order of your own using keyword arguments.
Order class with a default size and quantity, and creates three orders: one that uses both defaults, one that sets everything by position, and one that sets only the quantity by keyword.class Order:
def __init__(self, item, size="Medium", quantity=1):
self.item = item
self.size = size
self.quantity = quantity
def summary(self):
return str(self.quantity) + " x " + self.size + " " + self.item
print(Order("latte").summary())
print(Order("mocha", "Large", 2).summary())
print(Order("tea", quantity=3).summary())Order describes one drink order.item is required. size and quantity have default values, so they are optional.summary builds a one-line description of the order.str() converts the number to text so it can be joined with the other strings using +.1 x Medium latte.2 x Large mocha.quantity=3 sets only the quantity, and the size keeps its default. The output is 3 x Medium tea.Validating Data in the Constructor
The constructor is the best place to make sure an object starts out with sensible data. If a value is impossible, such as a GPA of 5.2, you can stop the creation of the object by raising an exception with raise ValueError(...). The object is then never created, so no invalid object can exist anywhere in your program.
Calling code can catch the exception with a try and except block and decide what to do, for example by showing an error message to the user. Checking the data once, at the door, is far simpler than checking it every time a method uses it. This idea is called failing early, and it makes bugs much easier to find.
Try It: Reject an Impossible GPA
Click Test My Code. Then change the second GPA to a valid number and see what happens.
Student class whose constructor refuses a GPA outside the range from 0 to 4.0. A valid student is created normally, and an invalid one raises an error that the program catches and reports.class Student:
def __init__(self, name, gpa):
if gpa < 0 or gpa > 4.0:
raise ValueError("GPA must be between 0 and 4.0")
self.name = name
self.gpa = gpa
good = Student("Olivia", 3.7)
print(good.name, good.gpa)
try:
bad = Student("Ethan", 5.2)
except ValueError as error:
print("Error:", error)Student describes a student with a name and a GPA.True when the GPA is below 0 or above 4.0, which is not allowed.raise ValueError(...) stops the constructor with an error message. No object is created.Olivia 3.7.try block lets the program attempt something that might fail.ValueError, and the variable bad is never assigned.except ValueError as error: catches the error and stores it in the variable error.Error: GPA must be between 0 and 4.0.Mutable Default Arguments
A default value is created only once, when the function is defined, and not each time the function is called. For numbers and strings that does not matter, because they cannot be changed. For a list or a dictionary, it matters a lot: every object created without that argument ends up sharing the same single list.
This is one of the most famous bugs in Python. The safe pattern is to use None as the default and to create a fresh list inside the constructor when no list was given. The example below builds two carts with a bad constructor and two with a good one so that you can see the difference with your own eyes.
Try It: The Shared Shopping Cart Bug
Click Test My Code. Then compare the two outputs and explain why they differ.
BadCart whose default list is shared by every cart and a GoodCart that creates a new list for each cart. It adds apples to one cart of each kind and prints the contents of the other cart.class BadCart:
def __init__(self, items=[]):
self.items = items
class GoodCart:
def __init__(self, items=None):
self.items = items if items is not None else []
a = BadCart()
b = BadCart()
a.items.append("apples")
print(b.items)
c = GoodCart()
d = GoodCart()
c.items.append("apples")
print(d.items)BadCart will show the problem with a mutable default.[] is created once, when the method is defined, and is reused for every call that omits items.BadCart without an argument stores a reference to that one shared list.GoodCart uses the recommended pattern.None, which is immutable and safe to share.items was not given, a brand new empty list is created for this object. Otherwise the given list is used.a receives the shared default list.b receives the very same shared list.b was never touched, but its list contains apples. The output is ['apples'].c gets its own new list.d gets a different new list.c only.[].Method Chaining by Returning self
If a method ends with return self, the caller gets the same object back and can immediately call another method on it. Calls can then be strung together in a single line, such as Sandwich("Sourdough").add("turkey").add("swiss"). This style is called method chaining.
It is popular in code that builds up an object step by step, because the result reads almost like a sentence. The constructor also appears in the chain: Sandwich("Sourdough") creates the object, and each add() call changes it and returns it. Use chaining where it makes the code clearer, and avoid it when it would make a line hard to read.
Try It: Build a Sandwich in One Line
Click Test My Code. Then add one more topping to the chain.
Sandwich class whose add() method returns self, builds a sandwich with three chained calls, and prints it using a __str__ method.class Sandwich:
def __init__(self, bread):
self.bread = bread
self.toppings = []
def add(self, topping):
self.toppings.append(topping)
return self
def __str__(self):
return self.bread + " with " + ", ".join(self.toppings)
lunch = Sandwich("Sourdough").add("turkey").add("swiss").add("tomato")
print(lunch)Sandwich will be built up one topping at a time.add receives one topping.self hands back the same sandwich, so another method can be called on the result.__str__ controls how the object looks when it is printed.", ".join(...) glues the toppings together with a comma and a space between them.add() returns the same object to the next call in the chain.Sourdough with turkey, swiss, tomato.Alternative Constructors with @classmethod
A class can have only one __init__ method, but sometimes you want to create objects from different kinds of input, such as a full name in one string. The solution is an alternative constructor: a method marked with @classmethod that builds and returns an object. By convention the first parameter of a class method is named cls.
While self stands for an object, cls stands for the class itself. Calling cls(first, last) inside the method is the same as calling Person(first, last), but it also works for child classes that inherit from Person. Names such as from_full_name or from_string are the usual style for these helper constructors.
Try It: Create a Person from a Full Name
Click Test My Code. Then create a person from your own name.
Person class with a normal constructor and an alternative constructor that splits a full name, creates a person with it, and prints a greeting and the stored names.class Person:
def __init__(self, first, last):
self.first = first
self.last = last
@classmethod
def from_full_name(cls, full_name):
first, last = full_name.split()
return cls(first, last)
def greet(self):
return "Hello, " + self.first + " " + self.last
mia = Person.from_full_name("Mia Johnson")
print(mia.greet())
print(mia.first, mia.last)Person stores a first name and a last name.@classmethod tells Python that the next method receives the class, not an object, as its first argument.cls is the class itself, and full_name is the text to read.split() breaks "Mia Johnson" at the space, and the two pieces are unpacked into first and last.cls(first, last) calls the normal constructor and returns the finished object.greet is an ordinary method that receives self.Person.Hello, Mia Johnson.Mia Johnson.Using Constructors with input()
Constructors are a perfect place to turn raw input into a ready-to-use object. You read a line with input(), split it, convert the numbers, and pass them to the class. The constructor can then do any setup work, such as calculating a value that depends on the others, so that the object arrives fully prepared.
In the example below the constructor computes a runner’s pace once and stores it as an attribute, so the rest of the program can simply read runner.pace. Remember that input() always returns text, so convert numbers with float() before passing them in, and make sure the number of miles is not zero.
Try It: Calculate a Runner’s Pace in Central Park
The Program Input box is already filled with one line: Madison 5 40. Click Run Code straight away, then try your own name, distance in miles, and time in minutes.
Runner object whose constructor calculates the pace in minutes per mile, and prints a report and the stored pace.class Runner:
def __init__(self, name, miles, minutes):
self.name = name
self.miles = miles
self.minutes = minutes
self.pace = round(minutes / miles, 2)
def report(self):
return self.name + " ran " + str(self.miles) + " miles at " + str(self.pace) + " min/mile"
line = input("Name, miles, and minutes: ")
name, miles, minutes = line.split()
runner = Runner(name, float(miles), float(minutes))
print(runner.report())
print("Pace attribute:", runner.pace)Runner describes one run.self.pace, so it is ready as soon as the object exists.report builds a sentence from the object’s attributes.str() converts the numbers to text so they can be joined with +.input() reads the first line of the Program Input box as one string, such as "Madison 5 40".split() breaks the text at the spaces, and the three pieces are unpacked into name, miles, and minutes. All three are still strings.float() before they reach the constructor, which calculates the pace of 40 divided by 5.Madison ran 5.0 miles at 8.0 min/mile.Pace attribute: 8.0.Tip: A good test for a constructor is to ask: after __init__ finishes, does the object have every attribute that its methods need? If the answer is yes, the object is complete and safe to use.
Common Mistakes with Constructors and self
Almost every beginner makes the same few mistakes with constructors and self, and the error messages can look confusing at first. The good news is that the causes are simple once you know them. When something goes wrong, check the parameter list of __init__, the line where you create the object, and the use of self. in front of each attribute.
- Leaving out self:
def __init__(name):raises aTypeError, because Python passes the new object as the first argument. - Forgetting self. on an attribute:
name = namedoes nothing useful. Writeself.name = nameto store the value on the object. - Misspelling __init__: names such as
_init_,init, or__innit__are ordinary methods, so the constructor never runs. - Wrong number of arguments:
Pet("Buddy")raises aTypeErrorabout a missing argument when the constructor needs two. - Returning a value from __init__:
return 5raises aTypeError, because the constructor must returnNone. - Mutable default arguments:
def __init__(self, items=[])shares one list between all objects. UseNoneinstead. - Calling __init__ again by hand:
obj.__init__(...)works but is almost never a good idea. Create a new object instead. - Forgetting that self is not typed in a call: write
clicks.hit(), notclicks.hit(clicks).
Good Habits for Writing Constructors
A good constructor is short, predictable, and does only the work needed to get the object ready. It stores the incoming values, checks them if necessary, and prepares any values that depend on them. Following these habits keeps your classes easy to read and your objects reliable from the very first moment.
- Always name the first parameter
self, so every Python reader recognizes it immediately. - Create every attribute that the class uses inside
__init__, so no object is ever missing one. - Validate important values in the constructor and raise
ValueErrororTypeErrorfor bad input. - Use
Noneas the default for lists, dictionaries, and sets, and create the real object inside the constructor. - Keep constructors light. Avoid printing, reading files, or asking for input inside
__init__. - Use
@classmethodalternative constructors such asfrom_full_name()instead of making one constructor handle many input formats. - Give parameters the same name as the attribute they fill, as in
self.name = name, for clarity.
Key Takeaways
Constructors and self are the heart of every Python class. The constructor prepares each new object, and self connects every method to the object it works on. Review the points below before moving on to inheritance, where a child class reuses the constructor of its parent.
__init__is the constructor. It runs automatically when you call the class and sets up the new object.selfis the object itself. Python passes it as the first argument of every method call.self.name = namestores a parameter as a permanent attribute of the object.- Constructor parameters can have defaults, and callers can use keyword arguments to set them.
- Raise an exception in the constructor to refuse invalid data.
- Never use a mutable default such as
[]. UseNoneand create the object inside. - A method that returns
selfallows method chaining. - A
@classmethodwithclscreates alternative constructors.
Frequently Asked Questions
The ideas behind constructors and self raise a few questions again and again, especially for students who are new to classes. The answers below give short, clear explanations that build on the examples you practiced. Open a question to read the answer, and run the matching example again if you would like to see it in action.
What is a constructor in Python?
A constructor is a special method named __init__ that Python runs automatically when you create an object from a class. It receives the new object as self, together with any arguments you pass, and it normally stores them as attributes so that the object starts with the data it needs.
What does self mean in Python?
self is the first parameter of an instance method, and it refers to the object the method is working on. Python passes it automatically, so clicks.hit() is the same as Counter.hit(clicks). Inside the method, self.count means the count attribute of that particular object.
Is self a keyword in Python?
No. self is only a convention, and technically you could use another name for the first parameter. However, every Python programmer expects it to be called self, so you should always use that name to keep your code readable.
Why do I write self.name = name in __init__?
The parameter name is a local variable that disappears when the constructor ends. Writing self.name = name copies the value into an attribute stored on the object, so it stays available to every other method for as long as the object exists.
Can __init__ return a value?
No. The constructor must return None, and trying to return anything else raises a TypeError. The object itself is created and returned by Python after __init__ finishes. If you need to refuse bad data, raise an exception instead of returning a value.
Can a Python class have more than one constructor?
A class has only one __init__ method, but you can use default values and keyword arguments to make it flexible. For completely different kinds of input, add alternative constructors with the @classmethod decorator, such as Person.from_full_name(“Mia Johnson”), which build and return an object.
What is the difference between __init__ and __new__?
__new__ creates the new, empty object and returns it, and __init__ then sets up that object with its starting values. Almost every class only needs __init__. You use __new__ only in advanced cases, such as controlling how many objects can be created.
What is the difference between self and cls?
self refers to one particular object and is used in ordinary instance methods. cls refers to the class itself and is used in methods marked with @classmethod. A class method can call cls(…) to create a new object, which makes it ideal for alternative constructors.