1. Basic Concepts ¶
In Python, classes allow you to create custom data types and bundle data (attributes) with behaviors (methods).
1.1 Defining a Class¶
In [7]:
Copied!
class Animal:
def __init__(self, name, species):
self.name = name # instance attribute
self.species = species
def make_sound(self):
print("<generic animal sound>")
# Instantiate the class
dog = Animal("Fido", "Canine")
print(dog.name, dog.species)
dog.make_sound()
class Animal:
def __init__(self, name, species):
self.name = name # instance attribute
self.species = species
def make_sound(self):
print("")
# Instantiate the class
dog = Animal("Fido", "Canine")
print(dog.name, dog.species)
dog.make_sound()
Fido Canine <generic animal sound>
1.2 Inheritance¶
Inheritance enables a new class (child) to inherit attributes and methods from an existing class (parent).
In [8]:
Copied!
class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Canine")
def make_sound(self):
print("Woof!")
my_dog = Dog("Rex")
print(my_dog.name, my_dog.species)
my_dog.make_sound()
class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Canine")
def make_sound(self):
print("Woof!")
my_dog = Dog("Rex")
print(my_dog.name, my_dog.species)
my_dog.make_sound()
Rex Canine Woof!
In [9]:
Copied!
class MathUtils:
PI = 3.14159 # class attribute
@classmethod
def circle_area(cls, radius):
return cls.PI * (radius ** 2)
@staticmethod
def add(a, b):
return a + b
# Using class and static methods
print(MathUtils.circle_area(5))
print(MathUtils.add(10, 20))
class MathUtils:
PI = 3.14159 # class attribute
@classmethod
def circle_area(cls, radius):
return cls.PI * (radius ** 2)
@staticmethod
def add(a, b):
return a + b
# Using class and static methods
print(MathUtils.circle_area(5))
print(MathUtils.add(10, 20))
78.53975 30
2.2 Dunder Methods (Magic Methods)¶
Dunder methods allow classes to integrate with Python’s built-in operations (like str()
, len()
, arithmetic, etc.).
In [10]:
Copied!
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(2, 3)
v2 = Vector(4, 1)
v3 = v1 + v2
print(v3)
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(2, 3)
v2 = Vector(4, 1)
v3 = v1 + v2
print(v3)
Vector(6, 4)
2.3 Composition vs Inheritance¶
Composition is an alternative to inheritance. Instead of inheriting from a class, you hold an instance of another class as an attribute.
In [11]:
Copied!
class Engine:
def start(self):
print("Engine starts.")
def stop(self):
print("Engine stops.")
class Car:
def __init__(self):
self.engine = Engine() # Composition
def drive(self):
self.engine.start()
print("Car is driving...")
self.engine.stop()
my_car = Car()
my_car.drive()
class Engine:
def start(self):
print("Engine starts.")
def stop(self):
print("Engine stops.")
class Car:
def __init__(self):
self.engine = Engine() # Composition
def drive(self):
self.engine.start()
print("Car is driving...")
self.engine.stop()
my_car = Car()
my_car.drive()
Engine starts. Car is driving... Engine stops.
3. Exercises ¶
Work on the following exercises to consolidate your understanding of Python classes.
Exercise 1: Creating a Book Class¶
- Create a
Book
class with attributes:title
,author
,pages
. - Implement a
__str__
method that returns a string in the format:"Book(title='...', author='...', pages=...)"
. - Instantiate a few
Book
objects and print them.
In [13]:
Copied!
# Your solution here
# Your solution here
Exercise 2: Inheritance¶
- Create a
Vehicle
parent class with attributes:make
,model
, and a methoddrive()
. - Create a
Truck
child class that inherits fromVehicle
. Add an attributecapacity
and overridedrive()
to print a different message. - Instantiate both classes and call their
drive()
methods.
In [14]:
Copied!
# Your solution here
class Vehicle:
pass
class Truck(Vehicle):
pass
# Example usage:
# car = Vehicle("Toyota", "Camry")
# car.drive()
# pickup = Truck("Ford", "F-150", 1000)
# pickup.drive()
# Your solution here
class Vehicle:
pass
class Truck(Vehicle):
pass
# Example usage:
# car = Vehicle("Toyota", "Camry")
# car.drive()
# pickup = Truck("Ford", "F-150", 1000)
# pickup.drive()
Exercise 3: Class/Static Methods¶
- Define a class
MathOperations
with a class methodfrom_list(values)
that returns an instance with some aggregated result (e.g., sum of the list), and a static methodmultiply(a, b)
. - Demonstrate usage by creating an instance using
from_list
and callingmultiply
.
In [15]:
Copied!
# Your code here
class MathOperations:
pass
# Example usage:
# ops = MathOperations.from_list([1, 2, 3])
# print(ops)
# print(MathOperations.multiply(3, 5))
# Your code here
class MathOperations:
pass
# Example usage:
# ops = MathOperations.from_list([1, 2, 3])
# print(ops)
# print(MathOperations.multiply(3, 5))
4. Real-World Applications ¶
Frameworks Using OOP¶
- Django: A popular web framework that relies heavily on classes (models, views) to structure large applications.
- Flask Extensions: Often define extension classes for plugin functionality.
NLP Libraries¶
- spaCy: Defines classes like
Doc
,Token
,Span
for text processing. - NLTK: Many classes for parsing, tokenization, etc.
Data Science¶
- scikit-learn: Almost every algorithm is an object with
.fit()
and.predict()
methods. - PyTorch / TensorFlow: Model classes that define neural network architectures.
Classes are the foundation of these libraries, making it easier to organize and extend complex functionality.