Script Valley
Python: Complete Language Course
Object-Oriented ProgrammingLesson 4.1

Python classes and objects โ€” the basics

class definition, __init__ method, instance attributes, class attributes, self parameter, instantiation, instance methods

Classes and Objects

A class is a blueprint. An object (instance) is a concrete version of that blueprint with its own data. __init__ runs automatically when you create an instance.

class Dog:
    species = "Canis familiaris"  # class attribute

    def __init__(self, name, age):
        self.name = name   # instance attributes
        self.age = age

    def bark(self):
        return f"{self.name} says Woof!"

dog1 = Dog("Rex", 4)
dog2 = Dog("Bella", 2)

print(dog1.bark())         # Rex says Woof!
print(dog2.name)           # Bella
print(Dog.species)         # Canis familiaris
print(dog1.species)        # also works

Class vs Instance Attributes

Class attributes are shared across all instances. If you set an instance attribute with the same name, it shadows the class attribute for that instance only. Modify class attributes through the class itself, not an instance โ€” otherwise you create an instance attribute with the same name.

dog1.species = "changed"   # creates instance attr
print(Dog.species)         # still "Canis familiaris"
print(dog2.species)        # still "Canis familiaris"

Classes model real-world entities with both data (attributes) and behaviour (methods). The self parameter is not a keyword โ€” it is a strong convention. You could name it anything, but self is universal across Python codebases and must always be the first parameter of instance methods. The __init__ method is not a constructor in the C++ sense โ€” the object already exists when __init__ runs; it is an initialiser. For more control over object creation itself, override __new__, though this is rarely needed outside of metaclass work.

Up next

Python inheritance and method overriding

Sign in to track progress

Python classes and objects โ€” the basics โ€” Object-Oriented Programming โ€” Python: Complete Language Course โ€” Script Valley โ€” Script Valley