Lesson 16 of 30
Object-Oriented Programming – Classes
Defining classes, creating objects, instance variables, and methods.
What is a Class?
A class is a blueprint for creating objects. An object is an instance of a class containing both data (attributes) and behaviour (methods).
Defining a Class
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says: Woof!")
def __str__(self):
return f"Dog({self.name}, {self.breed})"
rex = Dog("Rex", "German Shepherd")
rex.bark()
print(rex)
Class vs Instance Attributes
class Counter:
count = 0 # class attribute (shared)
def __init__(self):
Counter.count += 1
self.id = Counter.count # instance attribute
a = Counter()
b = Counter()
print(Counter.count) # 2
Methods
- Instance methods — take
selfas first parameter. - Class methods — decorated with
@classmethod, receivecls. - Static methods — decorated with
@staticmethod, receive neither.
class MathUtils:
@staticmethod
def is_even(n):
return n % 2 == 0
print(MathUtils.is_even(4)) # True