Academic Block

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 class keyword 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.name inside 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.attribute reads a value and object.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.

What this code does: It defines a 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)

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.

What this code does: It creates a student object, prints and changes its major, checks for a missing GPA attribute, adds the GPA with 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"))

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.

What this code does: It defines a 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())

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.

What this code does: It creates three city objects in a list, prints each one, finds the city with the largest population using a lambda, and adds up the populations of all three cities.
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)

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.

What this code does: It creates a playlist object, makes an alias and shows that renaming through the alias changes the original, then makes a deep copy and shows that adding a song to the copy leaves the original untouched.
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)

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.

What this code does: It defines a 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)

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.

What this code does: It defines a 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())

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.

What this code does: It reads a destination, a distance, and a fuel economy, creates a 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()))
Tip: Use vars(obj) to see all of an object’s attributes as a dictionary, and dir(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 a TypeError when called, because Python passes the object as the first argument.
  • Forgetting self. before an attribute: writing length = 5 inside a method creates a local variable, while self.length = 5 changes the object.
  • Forgetting the parentheses: trip = Trip stores the class, and trip = Trip("Denver", 900, 30) creates an object. Likewise, trip.cost without 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. Use None and create the list inside the method.
  • Confusing an alias with a copy: b = a does not copy the object. Use copy.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. Use str() 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 City or Playlist, and methods with verbs, such as expand().
  • 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(), and del to work with them by name.
  • Variables hold references, so b = a creates an alias, and copy.deepcopy() creates an independent copy.
  • == tests equality, is tests 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.

Ready for the next step?Look closely at the constructor and the meaning of self.
Next: Constructors & self →