Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 149 ยท Object-Oriented Programming

Classes and Objects

Start object-oriented programming in Python. Define classes, create objects, set attributes in __init__, write methods with self, and use class attributes.

So far you've stored data in strings, lists and dictionaries, and written functions that work on that data. That goes a long way. But as programs grow, you'll notice data and the functions that handle it belong together: a bank account has a balance and ways to deposit and withdraw; a playlist has songs and ways to shuffle and add them.

A class lets you bundle data and behavior into your own type. Each value you create from a class is an object (also called an instance). This style of programming is called object-oriented programming (OOP), and in this lesson you'll learn its core pieces: class, __init__, attributes, methods and self.

You've been using objects all along

Everything in Python is an object, and every object has a type, which is its class:

Python Built-in objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

list and str are classes. words is one list object and name is one string object. append() and title() are methods: functions that belong to the class and operate on a particular object. Writing your own class means creating a new type that works the same way.

Defining a class and creating objects

Here's the smallest useful class. By convention, class names use CapWords (BankAccount, Song), while functions and variables use snake_case:

Python A first class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Let's take it apart:

  • class Dog: defines a new type. The indented block holds its methods.
  • Dog("Rex", "beagle") calls the class like a function. Python creates a new, empty object and then runs __init__ to set it up.
  • __init__ (with two underscores on each side) is the initializer. It runs automatically for every new object and gives it its starting data.
  • self.name = name creates an attribute: a variable that lives inside this particular object.
  • add_trick and describe are methods. You call them with dot syntax: rex.add_trick("sit").

rex and luna are two separate objects. Each has its own name, breed and tricks list, which is why teaching Rex a trick doesn't affect Luna.

What is self?

Every method's first parameter is the object it was called on. By strong convention it's named self. When you write

Python
rex.add_trick("sit")

Python actually runs

Python
Dog.add_trick(rex, "sit")

So inside the method, self is rex, and self.tricks is Rex's list. That's how one method definition can serve every dog: it always works on whichever object it was called on.

Watch out: forgetting self is the most common class mistake. If you define def describe(): without self, calling rex.describe() raises TypeError: Dog.describe() takes 0 positional arguments but 1 was given. That "1 was given" is the object Python passed automatically. Likewise, writing name = name instead of self.name = name in __init__ creates a local variable that vanishes when __init__ ends.

Methods that change state

Objects really shine when methods keep their data consistent. A bank account shouldn't let anyone set a negative balance by accident, so the methods enforce the rules:

Python A bank account

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how much the methods hide. The code that uses the account just says account.deposit(25); it doesn't need to know about the history list or the validation. balance=0.0 is a normal default parameter, so BankAccount("Tomas") starts with an empty account. The methods raise exceptions for invalid operations, exactly as you learned in Raising Exceptions.

Attributes are flexible

Attributes are ordinary values you can read and assign with dot syntax. You can even add new ones to an object after it's created, though it's best to create all of them in __init__ so every object has the same shape and readers can see them in one place.

Python has no truly private attributes. Instead, a leading underscore, as in self._pin, is a widely respected convention that means "internal; don't touch this from outside the class". If you want to control how an attribute is read or written, use a property, covered in Properties.

Class attributes versus instance attributes

Attributes set on self belong to one object. Attributes defined directly in the class body belong to the class and are shared by all its instances:

Python Class and instance attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When you read self.venue, Python looks on the object first and then on its class. That's why a.venue finds the shared value. But assigning b.venue = ... creates a new attribute on b that hides the class one; it doesn't change the class. To update the shared counter, the code writes Ticket.sold += 1 explicitly, not self.sold += 1.

Watch out: never use a mutable class attribute, like tricks = [] in the class body, for per-object data. Every instance would share the same list, so adding a trick to one dog would add it to all of them. Create mutable attributes in __init__ with self.tricks = [].

Printing objects nicely

If you print() an object of your own class, you get something like <__main__.Dog object at 0x10a3f2b50>. That's Python's default description: the class name and a memory address. To control it, define a __repr__ method that returns a string:

Python
class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def __repr__(self):
        return f"Dog(name={self.name!r}, breed={self.breed!r})"

print(Dog("Rex", "beagle"))   # Dog(name='Rex', breed='beagle')

__init__ and __repr__ are special methods (or "dunder" methods, for "double underscore"). Python calls them for you at particular moments. There are many more, letting your objects support ==, <, len() and even +; see Special (Dunder) Methods. And for classes that mostly hold data, Data Classes can write __init__ and __repr__ for you.

When to write a class

Classes are a tool, not a requirement. A good rule of thumb:

  • Use a class when you have data plus several operations that must keep that data valid, or when you'll create many objects of the same kind.
  • Use a function when you just transform input into output with no state to remember.
  • Use a dictionary, tuple or data class when you only need to group a few values together without behavior.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does a class's init method run?

    Calling the class, as in Dog("Rex", "beagle"), creates a new object and runs init on it to set up its attributes.
  2. 2. Inside a method, what does self refer to?

    obj.method(x) runs Class.method(obj, x), so self is the object before the dot.
  3. 3. You defined def bark(): in a class, without self. What happens when you call rex.bark()?

    Python always passes the instance as the first argument, so a method without self receives 1 argument but expects 0.
  4. 4. A class has count = 0 in its body. Which statement updates the shared count for all instances?

    Assigning to self.count creates a separate instance attribute. Update the class attribute through the class name.
  5. 5. Where should a per-object list such as a list of tricks be created?

    A list in the class body is shared by every instance. Creating it in init gives each object its own list.

Summary

  • A class defines a new type; calling it creates objects (instances) of that type.
  • __init__(self, ...) runs for every new object and sets its starting attributes with self.name = value.
  • Methods are functions defined in the class; self is the object they were called on, passed automatically.
  • Instance attributes belong to one object; class attributes in the class body are shared. Never use a mutable class attribute for per-object data.
  • A leading underscore marks an attribute as internal by convention.
  • __repr__ controls how an object prints; it's one of many special methods.

Next: Instance, Class and Static Methods, where you'll learn @classmethod, @staticmethod and alternative constructors.