Understanding Classes and Objects in Python: Concepts, Inheritance, Special Methods, and Advanced Examples
This article introduces Python's class and object fundamentals, covering class definitions, instance and class variables, inheritance, special (dunder) methods, and advanced examples such as encapsulation, operator overloading, and the use of class and static methods, all illustrated with clear code snippets.
Preface: In Python, classes and objects are core concepts of object‑oriented programming; understanding them is essential for writing well‑structured, maintainable code.
Concept: A class is a user‑defined type describing a set of attributes (data members) and behaviors (methods). The class definition serves as a blueprint for creating objects.
Definition of a class example:
class MyClass:
# class variable, shared by all instances
class_var = "This is a class variable."
def __init__(self, instance_var):
# instance variable, unique to each instance
self.instance_var = instance_var
def method(self):
# instance method can access instance variables
print(f"This is an instance method. Instance variable: {self.instance_var}")Object concept: An object is an instance of a class; creating an instance allocates memory and initializes its attributes.
Creating an object example:
# Create an instance of MyClass
obj = MyClass("This is an instance variable.")
print(obj.instance_var) # Output: This is an instance variable.
obj.method() # Output: This is an instance method. Instance variable: This is an instance variable.Class members: instance variables, class variables, and methods are described.
Inheritance: Inheritance allows a subclass to acquire attributes and methods from a parent class, with the ability to override or extend behavior.
class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement this abstract method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!Special methods (magic/dunder) such as __init__, __str__, __repr__, __eq__, __lt__, __add__ define object behavior.
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1) # Output: Point(1, 2)
print(repr(p1)) # Output: Point(x=1, y=2)
print(p1 == p2) # Output: False
print(p1 + p2) # Output: Point(4, 6)Advanced examples: encapsulation with private attributes, inheritance and polymorphism, operator overloading, class methods and static methods.
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
raise ValueError("Deposit amount must be positive.")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
else:
raise ValueError("Withdrawal amount must be positive and less than or equal to the current balance.")
def get_balance(self):
return self.__balance
account = BankAccount()
account.deposit(1000)
account.withdraw(500)
print(account.get_balance()) # Output: 500 class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this abstract method")
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Output: Buddy says Woof!
print(cat.speak()) # Output: Whiskers says Meow!
def animal_sound(animal):
print(animal.speak())
animal_sound(dog)
animal_sound(cat) class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
result_add = v1 + v2
print(result_add) # Output: Vector(4, 6)
result_sub = v1 - v2
print(result_sub) # Output: Vector(-2, -2) class Employee:
num_of_employees = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = f"{first}.{last}@company.com"
self.pay = pay
Employee.num_of_employees += 1
def fullname(self):
return f"{self.first} {self.last}"
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split("-")
return cls(first, last, pay)
@staticmethod
def is_workday(day):
return day.weekday() < 5
emp_1 = Employee("John", "Doe", 60000)
emp_2 = Employee("Jane", "Smith", 70000)
Employee.set_raise_amount(1.05)
print(Employee.raise_amount) # Output: 1.05
emp_str_1 = "Michael-Brown-70000"
new_emp = Employee.from_string(emp_str_1)
print(new_emp.email) # Output: [email protected]
import datetime
my_date = datetime.date(2024, 9, 16)
print(Employee.is_workday(my_date)) # Output: True or FalseTest Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.