π Class
Good to know
βοΈ A class is a blueprint for creating objects (instances) with data (attributes) and behavior (methods). Most of the time youβll work with instance methods and init to set up data.
Basic Class & Object
Define a class with class, then create an object (instance) by calling it like a function.
class Dog:
def bark(self): # Function
print("Woof!")
buddy = Dog() # create an instance
buddy.bark() # call method -> Woof!init and Instance Attributes (Constructor)
init runs automatically when you create an object and usually sets up attributes.
class Dog:
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age
dog = Dog("Buddy", 5)
print(dog.name, dog.age) # Buddy 5The self Parameter
self is a reference to the current object and is how methods access attributes. Itβs needed when you wanna access instance variables inside the class itself just like this in java.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} says woof!")
dog = Dog("Luna")
dog.speak() # Luna says woof!Class Attributes vs Instance Attributes
Class attributes are shared by all instances; instance attributes belong to one object.
class Dog:
species = "Canis familiaris" # class attribute
def __init__(self, name):
self.name = name # instance attribute
dog1 = Dog("Max")
dog2 = Dog("Bella")
print(dog1.species) # Canis familiaris
print(dog2.name) # BellaMethods: Instance, Class, Static
Use @classmethod and @staticmethod for alternate constructors or utility functions.
class Dog:
def __init__(self, name):
self.name = name
def speak(self): # instance method
print(self.name, "barks")
@classmethod
def from_dict(cls, data): # class method
return cls(data["name"])
@staticmethod
def is_dog_food(food): # static method
return food in ["meat", "bones"]
dog = Dog.from_dict({"name": "Rex"})
dog.speak() # Rex barks
print(Dog.is_dog_food("meat")) # True** Quick Data Classes**
For simple βdata holderβ classes, dataclasses reduce boilerplate. This gives you init, repr, comparisons, and more for free.
from dataclasses import dataclass
@dataclass
class Dog:
name: str
age: int
dog = Dog("Kira", 2)
print(dog.name, dog.age)Inheritance (Extending a Class)
A subclass reuses and extends behavior of a parent class.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(self.name, "makes a sound")
class Dog(Animal): # Dog inherits from Animal
def speak(self):
print(self.name, "barks!")
dog = Dog("Milo")
dog.speak() # Milo barks!Using super() to Call Parent Logic
super() lets a subclass call methods (like init) from its parent.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, age):
super().__init__(name) # call Animal.__init__
self.age = age
dog = Dog("Nala", 3)
print(dog.name, dog.age) # Nala 3Nice String Representation (str) (to_string)
Define str for a human-readable representation (e.g. print(obj)).
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age} years)"
dog = Dog("Rocky", 4)
print(dog) # Rocky (4 years)