Codzy

Classes and objects

Object-oriented programming (OOP) groups data and actions into objects. A class is the blueprint: class Dog:. Each object created from it is an instance.

The constructor __init__ is called automatically when the object is created; it stores the data in self, which represents the object itself. Functions defined inside a class are called methods and always take self as their first parameter.

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

    def bark(self):
        return self.name + " says woof!"

rex = Dog("Rex", 3)
print(rex.name)
print(rex.bark())

Start the lesson