Python Classes and Objects
Classes and Objects Fundamentals
A class is a blueprint for creating objects. An object is an instance of a class that bundles together data (attributes) and behavior (methods).
Example
# Class definition and object creation
class Dog:
# Class attribute (shared by all instances)
species = "Canis familiaris"
# Constructor method
def __init__(self, name, age, breed):
# Instance attributes (unique per object)
self.name = name
self.age = age
self.breed = breed
# Instance method
def bark(self):
return f"{self.name} says woof!"
def get_info(self):
return f"{self.name} is a {self.age}-year-old {self.breed}"
# Special method for string representation
def __str__(self):
return self.get_info()
# Creating objects (instances)
dog1 = Dog("Buddy", 3, "Golden Retriever")
dog2 = Dog("Lucy", 5, "Poodle")
# Accessing attributes and methods
print(dog1.name)
print(dog2.species)
print(dog1.bark())
print(dog2.get_info())
print(dog1) # Calls __str__ method
Output
Buddy Canis familiaris Buddy says woof! Lucy is a 5-year-old Poodle Buddy is a 3-year-old Golden Retriever
Class Components
Component | Description | Example |
---|---|---|
Class Attributes | Variables shared across all instances | species = "Canis familiaris" |
Instance Attributes | Variables unique to each object | self.name = name |
Methods | Functions that define object behavior | def bark(self): |
Constructor | Special method called when creating objects | def __init__(self, name, age): |
Special Methods | Enable built-in operations | __str__, __len__ |
Access Modifiers
Python does not enforce access restrictions strictly. Instead, naming conventions are used to signal intended access levels:
Example
# Access modifier conventions in Python
class Employee:
def __init__(self, name, salary):
self.name = name # Public attribute
self._department = "IT" # Protected attribute (convention)
self.__salary = salary # Private attribute (name mangling)
def get_salary(self):
return f"Salary: ${self.__salary}"
def _get_department(self):
return self._department
emp = Employee("John", 50000)
# Public
print(emp.name)
# Protected (accessible but discouraged)
print(emp._department)
# Private (raises AttributeError if accessed directly)
print(emp.get_salary())
# Name mangling (not recommended)
print(emp._Employee__salary)
Output
John IT Salary: $50000 50000
Special Methods
Special methods (also called dunder methods) let objects integrate with Python’s built-in operations and operators.
Example
# Example of special methods
class Vector:
def __init__(self, x, y):
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 __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __len__(self):
return 2 # Always two components
v1 = Vector(2, 3)
v2 = Vector(1, 4)
print(v1 + v2)
print(v1 - v2)
print(v1 * 3)
print(len(v1))
Output
Vector(3, 7) Vector(1, -1) Vector(6, 9) 2