What is Python Class?
class Dog:
def __init__(self, name, age): # Constructor
self.name = name # Instance attribute
self.age = age # Instance attribute
def bark(self): # Instance method
print(f"{self.name} says Woof!")
def get_older(self, years):
self.age += years
- class Dog: defines a new class named Dog.
- __init__ is a special method called the constructor. It runs when you create a new object.
- self is a reference to the current instance of the class (required as the first parameter in instance methods).
- You create an object (instance) like this as shown below:
my_dog = Dog("Buddy", 3)
my_dog.bark() # Output: Buddy says Woof!
print(my_dog.age) # Output: 3
my_dog.get_older(2)
print(my_dog.age) # Output: 5
MethodsMethods are functions defined inside a class. There are three main types:
- Instance methods (most common)
- Take self as the first parameter.
- Can access and modify instance attributes.
- Class methods
- Take cls as the first parameter.
- Decorated with @classmethod.
- Operate on the class itself, not instances.
class Dog: species = "Canis familiaris" # Class attribute @classmethod def get_species(cls): return cls.species - Static methods
- Don’t take self or cls.
- Decorated with @staticmethod.
- Behave like regular functions but belong to the class’s namespace.
class Dog: @staticmethod def is_adult(age): return age >= 2
class Car:
def __init__(self):
self.speed = 0
self.color = "white"
def set_speed(self, speed):
self.speed = speed
def paint(self, color):
self.color = color
my_car = Car()
my_car.set_speed(100)
my_car.paint("red")
print(my_car.speed, my_car.color) # 100 red
Example with method chaining:
class Car:
def __init__(self):
self.speed = 0
self.color = "white"
def set_speed(self, speed):
self.speed = speed
return self # ? Important for chaining
def paint(self, color):
self.color = color
return self # ? Important for chaining
my_car = Car()
my_car.set_speed(100).paint("red") # Chain the calls
print(my_car.speed, my_car.color) # 100 red
You can chain as many methods as you want:
my_car.paint("blue").set_speed(200).paint("green")
Real-world examples of method chaining in Python:
- Strings (immutable, so they return a new string):
" hello world ".strip().upper().replace("WORLD", "PYTHON") # ? "HELLO PYTHON" - pandas DataFrames (very common):
df.query("age > 30").sort_values("name").drop_duplicates() - Requests library (some methods return self):
session.headers.update({...}).timeout(10).verify(False)
Key points for enabling chaining:
- The method should modify the object in place.
- The method must return self at the end.
- Avoid methods that naturally return something else (like len() or computations) unless you intentionally want to break the chain.
Summary
- Classes define objects with attributes and behavior.
- Methods are functions inside classes; instance methods use self.
- Method chaining makes code fluent and readable by having each method return self.
This pattern is widely used in Python libraries to create clean, expressive APIs.
