Python 101Free
CLASSES AND OOP

Classes and Instances

Bundling state and behavior into a custom type.

SECTION 01

Defining a class

When your program has several things with the same shape and the same behavior, you define a class to describe the pattern once. 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"
2 more sections

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in