Understanding and using classes and objects in Python, with examples and outputs.
- Basic class definition and object creation
- Class and instance variables
- Inheritance
- Encapsulation and property decorators
- Static and class methods
- Magic methods (dunder methods)
- Abstract base classes
1. Basic Class Definition and Object Creation
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
# Creating an object
my_dog = Dog("Buddy", 3)
print(f"My dog's name is {my_dog.name} and he is {my_dog.age} years old.")
print(my_dog.bark())
# Output:
# My dog's name is Buddy and he is 3 years old.
# Buddy says Woof!
2. Class and Instance Variables
class Cat:
species = "Felis catus" # Class variable
def __init__(self, name):
self.name = name # Instance variable
cat1 = Cat("Whiskers")
cat2 = Cat("Mittens")
print(f"{cat1.name} is a {Cat.species}")
print(f"{cat2.name} is also a {cat2.species}")
# Changing class variable
Cat.species = "Felis silvestris catus"
print(f"Updated species: {cat1.species}")
# Output:
# Whiskers is a Felis catus
# Mittens is also a Felis catus
# Updated species: Felis silvestris catus
3. Inheritance
class Animal:
def __init__(self, species):
self.species = species
def make_sound(self):
pass
class Dog(Animal):
def __init__(self, name):
super().__init__("Canis familiaris")
self.name = name
def make_sound(self):
return "Woof!"
class Cat(Animal):
def __init__(self, name):
super().__init__("Felis catus")
self.name = name
def make_sound(self):
return "Meow!"
dog = Dog("Rover")
cat = Cat("Whiskers")
print(f"{dog.name} is a {dog.species} and says {dog.make_sound()}")
print(f"{cat.name} is a {cat.species} and says {cat.make_sound()}")
# Output:
# Rover is a Canis familiaris and says Woof!
# Whiskers is a Felis catus and says Meow!
4. Encapsulation and Property Decorators
class BankAccount:
def __init__(self, balance):
self._balance = balance # Protected attribute
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Balance cannot be negative")
self._balance = value
account = BankAccount(1000)
print(f"Initial balance: ${account.balance}")
account.balance = 1500
print(f"Updated balance: ${account.balance}")
try:
account.balance = -500
except ValueError as e:
print(f"Error: {e}")
# Output:
# Initial balance: $1000
# Updated balance: $1500
# Error: Balance cannot be negative
5. Static and Class Methods
class MathOperations:
@staticmethod
def add(x, y):
return x + y
@classmethod
def multiply(cls, x, y):
return cls.add(x, 0) * y # Using the static method
print(f"5 + 3 = {MathOperations.add(5, 3)}")
print(f"4 * 6 = {MathOperations.multiply(4, 6)}")
# Output:
# 5 + 3 = 8
# 4 * 6 = 24
6. Magic Methods (Dunder Methods)
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f"{self.title} by {self.author}"
def __len__(self):
return self.pages
def __eq__(self, other):
if not isinstance(other, Book):
return False
return self.title == other.title and self.author == other.author
book1 = Book("Python Basics", "John Doe", 200)
book2 = Book("Python Basics", "John Doe", 200)
book3 = Book("Advanced Python", "Jane Smith", 300)
print(book1)
print(f"Number of pages: {len(book1)}")
print(f"book1 == book2: {book1 == book2}")
print(f"book1 == book3: {book1 == book3}")
# Output:
# Python Basics by John Doe
# Number of pages: 200
# book1 == book2: True
# book1 == book3: False
7. Abstract Base Classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2 * 3.14 * self.radius
rect = Rectangle(5, 3)
circle = Circle(4)
print(f"Rectangle area: {rect.area()}, perimeter: {rect.perimeter()}")
print(f"Circle area: {circle.area():.2f}, perimeter: {circle.perimeter():.2f}")
# Output:
# Rectangle area: 15, perimeter: 16
# Circle area: 50.24, perimeter: 25.12