Python Classes & ObjectsGet Certified
What Are Classes and Objects in Python?
A class is a blueprint that describes what a kind of thing looks like and what it can do. An object is one real thing built from that blueprint. If Student is the class, then Emily’s record and Jackson’s record are two separate objects, each with its own name, major, and grades.
In the previous lesson you saw the big ideas of object-oriented programming. This lesson slows down and looks closely at the two most important building blocks: how to write a class, and how to create and use objects from it. Almost everything in Python is already an object, including numbers, strings, and lists, so learning how objects work will help you understand the whole language more deeply.
- Class: created with the
classkeyword and a CapitalizedWords name. - Object (instance): created by calling the class like a function, as in
Student("Emily", "Biology"). - Instance attribute: data that belongs to one object, written
self.nameinside the class. - Class attribute: data shared by every object of the class, written directly in the class body.
- Method: a function inside a class whose first parameter is
self. - Dot notation:
object.attributereads a value andobject.method()runs an action. - Identity: two objects with identical data are still two different objects.
Defining a Class and Creating Objects
A class definition starts with the class keyword, the class name, and a colon. Everything indented underneath belongs to the class. A variable written directly in the class body is a class attribute, and every object created from the class can read it.
Each time you call the class, Python builds a brand new object. The objects are independent: giving one object its own value does not change the others. When you read an attribute, Python first looks on the object itself, and if it is not there, it looks on the class. That lookup rule explains the behavior in the example below.
Try It: Two Books from One Class
Click Test My Code to run the program. Then change the genre of the second book and run it again.
Book class with a shared genre, creates two book objects, and shows how giving one object its own genre leaves the other object and the class unchanged.class Book:
genre = "Fiction"
novel = Book()
manual = Book()
print(novel.genre, manual.genre)
manual.genre = "Technical"
print(novel.genre, manual.genre)
print(Book.genre)class Book: starts a new class. The indented lines below it belong to the class.genre is written directly in the class body, so it is a class attribute shared by every Book.Book() builds a new object, and the variable novel refers to it.manual.genre, so Python finds it on the class. The output is Fiction Fiction.manual object only. The class itself is not changed.manual now uses its own value, while novel still falls back on the class. The output is Fiction Technical.Fiction.Instance Attributes and the Constructor
Most of the time you want each object to start with its own data. The special method __init__, known as the constructor, runs automatically when an object is created and receives the values you pass in. Inside it, self.name = name stores a value on the new object. The next lesson explains __init__ and self in full detail.
Once an object exists, you can read an attribute with a dot, change it by assigning a new value, and remove it with del. Three built-in functions work with attributes by name: hasattr() checks whether an attribute exists, getattr() reads one, and setattr() creates or changes one. They are useful when the attribute name is stored in a variable.
Try It: Read, Change, and Remove Attributes
Click Test My Code. Then give the student a different major and add another attribute of your own.
setattr(), reads it with getattr(), and then deletes it.class Student:
def __init__(self, name, major):
self.name = name
self.major = major
emily = Student("Emily", "Biology")
print(emily.name, emily.major)
emily.major = "Chemistry"
print(emily.major)
print(hasattr(emily, "gpa"))
setattr(emily, "gpa", 3.8)
print(getattr(emily, "gpa"))
del emily.gpa
print(hasattr(emily, "gpa"))Student will describe one student.__init__ runs automatically when a student is created. self is the new object.self.name = name saves the name on the object."Emily" and "Biology" are passed to __init__ after self.Emily Biology.Chemistry.hasattr() returns True or False. The student has no GPA yet, so the output is False.setattr(emily, "gpa", 3.8) does the same as emily.gpa = 3.8, but the attribute name is given as text.getattr() reads the attribute whose name is given as text. The output is 3.8.del emily.gpa removes the attribute from the object.False.Methods: What an Object Can Do
A method is a function that belongs to a class. It always receives the object as its first parameter, named self by convention, which lets it read and change that object’s attributes. You call it with a dot, as in backyard.area(), and Python supplies self for you.
Methods can calculate and return a result, change the object’s data, or do both. Because the data and the code that works on it travel together, an object keeps its changes between calls. In the example below, calling expand() changes the garden, and the next call to area() sees the new size.
Try It: Measure a Backyard in Portland
Click Test My Code. Then change the size of the garden or the number of feet it expands.
Garden class with methods that calculate the area and the fence length, and a method that makes the garden bigger. The program prints the measurements before and after expanding.class Garden:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def fence_needed(self):
return 2 * (self.length + self.width)
def expand(self, feet):
self.length = self.length + feet
self.width = self.width + feet
backyard = Garden(20, 15)
print(backyard.area(), backyard.fence_needed())
backyard.expand(5)
print(backyard.area(), backyard.fence_needed())Garden describes a rectangular garden measured in feet.area is a method. It reads the object’s own attributes through self.fence_needed calculates the distance around the garden.expand receives a number of feet to add on every side of the rectangle.length attribute is increased.width attribute is increased. This method changes the object but returns nothing.300 70.500 90.Working with Collections of Objects
Objects are values like any other, so you can store them in lists, dictionaries, and tuples. A list of objects is one of the most common structures in real programs, such as a list of students, orders, or products. You can loop over the list and read each object’s attributes with a dot.
All the tools you already know work with objects too. The built-in functions max(), min(), and sorted() accept a key function, and a lambda can pick the attribute to compare. A generator expression can add up one attribute across all the objects. These patterns let you analyze groups of objects in just a few lines.
Try It: A List of Cities
Click Test My Code. Then add another city to the list. The populations are rounded, approximate figures.
class City:
def __init__(self, name, state, population):
self.name = name
self.state = state
self.population = population
cities = [City("Austin", "TX", 979000), City("Boston", "MA", 654000), City("Denver", "CO", 716000)]
for city in cities:
print(city.name + ", " + city.state, city.population)
biggest = max(cities, key=lambda c: c.population)
print("Largest:", biggest.name)
total = sum(c.population for c in cities)
print("Total:", total)City stores facts about one city.City(...) call creates one object, and the list holds all three.city.Austin, TX 979000, Boston, MA 654000, and Denver, CO 716000.max() calls the lambda on each object and compares the populations. It returns the whole object with the largest value.Largest: Austin.sum() adds them: 979000 + 654000 + 716000.Total: 2349000.Objects Are References: Aliases and Copies
A variable that holds an object does not contain the object itself. It holds a reference that points to it. When you write same = road_trip, you do not make a new object. You make a second name for the same one, called an alias. A change made through either name is visible through both.
To get a truly independent object, you must copy it. The copy module offers copy.copy(), which makes a shallow copy that still shares any inner lists, and copy.deepcopy(), which also copies everything inside. The operator is tests whether two names point to the very same object. This is an important idea, because many surprising bugs come from changing an object that another part of the program is still using.
Try It: Alias or Copy a Playlist
Click Test My Code. Then replace deepcopy with copy.copy and see how the output changes.
import copy
class Playlist:
def __init__(self, name, songs):
self.name = name
self.songs = songs
road_trip = Playlist("Road Trip", ["Track 1", "Track 2"])
same = road_trip
same.name = "Summer Drive"
print(road_trip.name)
print(same is road_trip)
clone = copy.deepcopy(road_trip)
clone.songs.append("Track 3")
print(road_trip.songs)
print(clone.songs)import copy gives access to copy.copy() and copy.deepcopy(). Modules are explained in a later lesson.Playlist holds a name and a list of songs."Road Trip" and two songs.same is not a new object. It is a second name for the object that road_trip already refers to.Summer Drive.is checks whether two names refer to the same object. The output is True.copy.deepcopy() creates a new playlist object and also a new list of songs inside it.['Track 1', 'Track 2'].['Track 1', 'Track 2', 'Track 3'].Printing, Comparing, and Identity
By default, printing an object shows only its class name and a memory address, and two objects with the same data are not considered equal. You can change both behaviors with special methods. __str__ returns friendly text for print(), and __repr__ returns a precise, developer-oriented description that appears inside lists and in the interactive prompt.
The special method __eq__ defines what == means for your class. Without it, == behaves like is and asks whether two names point to the same object. Keep the two ideas apart: equality asks “do these objects hold the same data?”, while identity asks “are these the very same object?”. A later lesson covers special methods in depth.
Try It: Compare Two Landmarks
Click Test My Code. Then change the city of the second landmark and watch the comparison change.
Landmark class with __str__, __repr__, and __eq__ methods, creates two separate landmark objects with the same data, and compares them with == and is.class Landmark:
def __init__(self, name, city):
self.name = name
self.city = city
def __str__(self):
return self.name + " in " + self.city
def __repr__(self):
return "Landmark(" + repr(self.name) + ", " + repr(self.city) + ")"
def __eq__(self, other):
return self.name == other.name and self.city == other.city
a = Landmark("Space Needle", "Seattle")
b = Landmark("Space Needle", "Seattle")
print(a)
print([a])
print(a == b, a is b)Landmark describes a famous place.__str__ controls what print() shows for the object.Space Needle in Seattle.__repr__ should show how the object could be created. Python uses it for objects inside a list.repr() adds quotation marks around each string, so the result looks like a constructor call.__eq__ decides what == means. The parameter other is the object on the right side of the comparison.print() uses __str__. The output is Space Needle in Seattle.__repr__. The output is [Landmark('Space Needle', 'Seattle')].a == b is True because the data matches, but a is b is False because they are two different objects. The output is True False.Objects That Contain Other Objects
Objects often contain other objects. A team has players, a school has students, and an order has items. This is called composition, and it is described as a “has a” relationship: a Team has Players. It is one of the most useful ways to build larger programs from small, simple classes.
The outer class usually keeps the inner objects in a list and offers methods to add to it and to summarize it. Notice that the list is created inside __init__, so every team gets its own list. Creating the list in the class body, or as a default argument, would make all teams share a single list, which is a classic beginner bug.
Try It: A Team with Players
Click Test My Code. Then add a third player to the team.
Player class and a Team class that holds a list of players. The program adds two players to a team and prints the number of players and the combined points.class Player:
def __init__(self, name, points):
self.name = name
self.points = points
class Team:
def __init__(self, name):
self.name = name
self.players = []
def add(self, player):
self.players.append(player)
def total_points(self):
return sum(p.points for p in self.players)
team = Team("Bulldogs")
team.add(Player("Liam", 28))
team.add(Player("Sophia", 34))
print(team.name, len(team.players))
print(team.total_points())Player is a small class that will be used inside another class.Team will hold a group of players.__init__.add receives a player object.total_points summarizes all the players on the team.points attribute, and sum() adds them."Bulldogs" starts with no players.Player object is created and handed to add().len(team.players) counts the player objects. The output is Bulldogs 2.62.Using Classes with input()
Classes work very well with user input. You read a line of text with input(), split it into pieces, convert the numbers, and use the pieces to create an object. After that, the object’s methods do the calculations, and the main program only prints the results. Keeping the rules inside the class means you can reuse them anywhere.
Remember that input() always returns text, so values such as miles and miles per gallon must be converted with float() before they are used in a calculation. A method can also have a parameter with a default value, such as the fuel price in this example. The caller can then override it when the price changes.
Try It: Plan a Road Trip
The Program Input box is already filled with one line: Denver 900 30. Click Run Code straight away, then try another destination, a distance in miles, and a fuel economy in miles per gallon.
Trip object, and prints the gallons of gas needed and the fuel cost at a default price of $3.50 per gallon.class Trip:
def __init__(self, destination, miles, mpg):
self.destination = destination
self.miles = miles
self.mpg = mpg
def gallons(self):
return self.miles / self.mpg
def cost(self, price=3.50):
return round(self.gallons() * price, 2)
line = input("Destination, miles, and mpg: ")
place, miles, mpg = line.split()
trip = Trip(place, float(miles), float(mpg))
print("Trip to", trip.destination)
print("Gallons:", trip.gallons())
print("Fuel cost: $" + str(trip.cost()))Trip describes one car trip.gallons calculates how much gas the trip needs.cost has a parameter price with a default value of 3.50 dollars per gallon.self.gallons(), multiplies by the price, and rounds to two decimal places. A method can call other methods on the same object.input() reads the first line of the Program Input box as one string, such as "Denver 900 30".split() breaks the text at the spaces, and the three pieces are unpacked into place, miles, and mpg. All three are still strings.float() before they are passed to the constructor.Trip to Denver.Gallons: 30.0.Fuel cost: $105.0.Tip: Usevars(obj)to see all of an object’s attributes as a dictionary, anddir(obj)to list every attribute and method it has. Both are very helpful when you are debugging.
Common Mistakes with Classes and Objects
Classes bring a few new rules, and most beginners run into the same handful of errors. Python’s messages are usually helpful, so read the last line of the error first. Look carefully at the first line of each method, at the line where you create the object, and at every place where you type an attribute name.
- Forgetting self:
def area():inside a class raises aTypeErrorwhen called, because Python passes the object as the first argument. - Forgetting self. before an attribute: writing
length = 5inside a method creates a local variable, whileself.length = 5changes the object. - Forgetting the parentheses:
trip = Tripstores the class, andtrip = Trip("Denver", 900, 30)creates an object. Likewise,trip.costwithout parentheses is the method itself, not its result. - Typos creating new attributes:
emily.mjaor = "Art"does not raise an error. It silently adds a new attribute, so double-check the spelling. - Sharing a mutable default:
def __init__(self, songs=[])makes every object share one list. UseNoneand create the list inside the method. - Confusing an alias with a copy:
b = adoes not copy the object. Usecopy.deepcopy(a)when you need an independent one. - Using == without __eq__: two separate objects with identical data are not equal until the class defines
__eq__. - Returning the wrong type from __str__:
__str__must return a string. Usestr()to convert numbers before joining them with+.
Good Habits for Designing Classes
A well-designed class is small, has a clear purpose, and is pleasant to use. These habits help you build classes that other people, and your future self, can understand quickly. Think about how the class will be used from the outside before you decide what goes inside it.
- Name classes with singular nouns in CapitalizedWords, such as
CityorPlaylist, and methods with verbs, such asexpand(). - Set every instance attribute inside
__init__so that each object starts in a complete state. - Give each class one clear responsibility. If a class does too many jobs, split it into smaller classes.
- Add a
__str__method, and ideally a__repr__method, so that objects are easy to read while you debug. - Use class attributes only for values that are truly shared, such as constants. Put changing data on the instance.
- Prefer methods that return values over methods that print, so the results can be reused.
- Use composition when one thing has other things, and keep class hierarchies simple.
Key Takeaways
Classes and objects are the core of object-oriented Python. A class describes the shape of the data and the actions, and each object carries its own copy of the data. Review the points below before moving on to constructors and self, where you will study the most important special method in detail.
- A class is a blueprint, and an object is an instance built from it by calling the class.
- Instance attributes belong to one object, and class attributes are shared by all objects.
- Methods are functions inside a class that receive the object as
self. - Use dot notation to read and change attributes, and
hasattr(),getattr(),setattr(), anddelto work with them by name. - Variables hold references, so
b = acreates an alias, andcopy.deepcopy()creates an independent copy. ==tests equality,istests identity, and__eq__lets a class define equality.__str__and__repr__control how objects are displayed.- Objects can contain other objects, which is called composition.
Frequently Asked Questions
Students often ask the same questions when they first create their own classes, especially about the difference between class and instance attributes and about copying objects. The answers below summarize the rules you practiced in the examples. Open a question to read the answer, and run the matching example again to see it in action.
How do I create a class in Python?
Use the class keyword, a CapitalizedWords name, and a colon, then indent the body. For example, class Student: followed by an __init__ method and other methods. The class is only a blueprint until you call it, as in Student(“Emily”, “Biology”), to create an object.
How do I create an object from a class?
Call the class like a function and pass any arguments that its __init__ method expects, such as garden = Garden(20, 15). Each call creates a new, independent object. Remember the parentheses, because writing only the class name stores the class itself.
What is the difference between an attribute and a method?
An attribute is a variable that belongs to an object or class and stores data, such as name or population. A method is a function defined inside a class that describes an action, such as area() or deposit(). You read attributes without parentheses and call methods with parentheses.
What is the difference between instance attributes and class attributes?
Instance attributes are created with self inside a method and belong to one object. Class attributes are written in the class body and are shared by all objects. If you assign to a class attribute name through an object, Python creates a new instance attribute and leaves the class attribute unchanged.
Why does b = a not copy my object?
In Python a variable holds a reference to an object, so b = a gives the same object a second name. Changes through either name affect the same object. Use copy.copy() for a shallow copy, or copy.deepcopy() when the object contains lists or other objects that must be copied as well.
Why is a == b False for two objects with the same data?
By default, == compares identity, so two separate objects are not equal even when their attributes match. Define an __eq__ method in the class to compare the attributes that matter. Note that is always tests whether two names point to the very same object.
What is the difference between __str__ and __repr__?
__str__ returns friendly text for people and is used by print() and str(). __repr__ returns an unambiguous description for developers, ideally one that looks like the code that creates the object, and is used inside lists and in the interactive prompt. If only __repr__ is defined, Python uses it for both.
How can I see all the attributes of an object?
Call vars(obj) to get a dictionary of the object’s own attributes and their values, or dir(obj) to list every attribute and method, including inherited ones. Use hasattr(obj, “name”) to check for one attribute and getattr(obj, “name”) to read it by name.