Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Classes and Objects

Learn how Python classes define objects, instance state, methods, class attributes, inheritance, and basic reuse with super().

Levels: Beginner ~25 min read

Basic

A class lets you define a new kind of object by combining data and behavior. An instance is a particular object created from that class. Python classes are useful when several values and operations naturally belong together.

Define a class

Create a class with the class keyword and an indented class body.

python
class Dog:
    pass

pet = Dog()
print(type(pet).__name__)

The class definition creates a new class, and calling the class creates an instance.

The class name is bound to the class object. Calling Dog() creates a new instance of that class.

Give each instance its own data

An instance can have attributes that store state. A common way to initialize that state is the __init__ method. Its first parameter refers to the instance being initialized; by convention that parameter is named self.

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

first = Dog("Fido")
second = Dog("Buddy")
print(first.name)
print(second.name)

Each call creates a separate instance with its own name attribute.

The assignment self.name = name creates an instance attribute. self is not a keyword; it is the conventional name for the instance parameter.

Define methods

Functions defined inside a class are normally used as methods. When you call a method through an instance, Python supplies that instance as the first argument.

python
class Counter:
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1

counter = Counter()
counter.increment()
counter.increment()
print(counter.value)

The method changes the state stored by that particular instance.

Inside a method, use self to read or change the instance attributes that belong to the object.

Class attributes and instance attributes

A class attribute is shared through the class and can be used by instances. An instance attribute belongs to one particular instance. Be especially careful with mutable class attributes such as lists, because the same object can be shared by every instance.

python
class Dog:
    species = "canine"

    def __init__(self, name):
        self.name = name

first = Dog("Fido")
second = Dog("Buddy")
print(first.species)
print(second.species)
print(first.name)
print(second.name)

species is defined on the class, while name is stored separately on each instance.

For per-instance mutable state, initialize a new object inside __init__ rather than using one mutable class attribute for all instances.

Build on another class with inheritance

Inheritance lets a new class reuse behavior from a base class. A derived class can add new behavior or override a method inherited from its base class.

python
class Animal:
    def speak(self):
        return "some sound"

class Dog(Animal):
    def speak(self):
        return "woof"

pet = Dog()
print(pet.speak())

Dog inherits from Animal and overrides its speak method.

An inherited attribute or method is found through the class hierarchy when it is not provided by the derived class itself.

Extend inherited behavior with super()

Sometimes an overriding method should add to the base implementation instead of replacing it completely. super() provides a way to access the next implementation in the class hierarchy.

python
class Animal:
    def __init__(self, name):
        self.name = name

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

pet = Dog("Fido", "collie")
print(pet.name, pet.breed)

super() lets the derived class reuse the base class initialization.

Check types and inheritance

Use isinstance() to ask whether an object is an instance of a class or its subclasses. Use issubclass() to ask whether one class derives from another.

python
class Animal:
    pass

class Dog(Animal):
    pass

pet = Dog()
print(isinstance(pet, Dog))
print(isinstance(pet, Animal))
print(issubclass(Dog, Animal))

These checks follow the inheritance relationship.

Keep the first classes lesson focused

Python classes support many advanced features, including multiple inheritance, properties, special methods, descriptors, dataclasses, and metaclasses. Those features deserve their own lessons when they become useful; they are not required to understand the basic class model introduced here.

A useful mental model is: a class defines a kind of object, an instance is one object of that kind, attributes hold state, methods define behavior, and inheritance lets one class build on another.

Was this page helpful?

Mark this learning resource complete to track your learning progress.