Python 101Free
CLASSES AND OOP

Classes and Instances

Bundling state and behavior into a custom type.

SECTION 01

Defining a class

A class is a blueprint for objects. The class body declares attributes (the data each instance will hold) and methods (the operations the instance can perform).

class Dog: introduces the class. Inside the body, def bark(self): defines a method. The method gets called on an instance, and the instance is passed in as the first argument by Python automatically.

Classes are the way Python lets you define a new type. Once you have a Dog class, you can build dogs, ask them to bark, store them in lists. The class itself is also an object, just one whose role is to be the template.

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

    def bark(self):
        return f"{self.name} says woof"
SECTION 02

Instances vs the class

Calling the class produces an instance. Dog("Rex") runs the class's constructor and gives you back a fresh Dog object. Each instance has its own attribute storage, distinct from every other instance and from the class itself.

Methods, on the other hand, live on the class. All instances share them. This is why you can have a thousand Dog instances without paying the memory cost of a thousand copies of bark.

So "the class" and "an instance of the class" are two different objects with different roles. The class is the template, instances are the things made from it. Methods belong to the template, attributes belong to each instance.

SECTION 03

self and method calls

When you write rex.bark(), Python rewrites it under the hood. The dot finds bark on the Dog class, and the call turns into Dog.bark(rex). The instance gets passed in as the first argument.

That first argument is what self refers to inside the method body. It is not a keyword. It is just the conventional name for whatever instance the method was called on. Other names would work, but every Python programmer would dislike you for using them.

This is the whole trick. Methods are functions that live on the class, and self is how each instance gets a chance to read its own data. self.name inside bark reaches into the specific dog the call started from, which is why one Dog can say its name and another Dog can say a different one.

python
rex = Dog("Rex")
rex.bark()         # 'Rex says woof'
Dog.bark(rex)      # same call, explicit form
NEXT →
Inheritance