In object-oriented programming (OOP), a class serves as a blueprint for creating objects, which are instances of that class. Defining a class in Python uses the class keyword, and instantiation creates a concrete object from that template.
class Cat:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def eat(self):
print(f"{self.name} enjoys eating fish.")
fluffy = Cat("Fluffy", "Persian")
print(fluffy.name) # Output: Fluffy
fluffy.eat() # Output: Fluffy enjoys eating fish.
Encapsulation
Encapsulation bundles data (attributes) and methods that operate on that data within a single unit—the class. Access to internal details is controlled through defined interfaces (methods or properties). The __init__ constructor initializes instence-specific attributes when an object is created.
Example implementation of a Person class:
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def shop(self):
print(f"{self.name},{self.age}岁,{self.gender},去西安赛格购物广场购物")
def study(self):
print(f"{self.name},{self.age}岁,{self.gender},在西部开源学习")
p1 = Person('小明', 18, '男')
p2 = Person('小王', 20, '男')
p3 = Person('小红', 22, '女')
p1.shop()
p2.shop()
p3.study()
Inheritance
Inheritance allows a new class (subclass) to reuse, extend, or modify behavior defined in an existing class (superclass). The subclass inherits all attributes and methods of the parent unless explicitly overridden.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def study(self):
print(f"{self.name} is studying.")
class MathStudent(Student):
pass
alice = MathStudent("Alice", 20)
alice.study() # Inherited method
Method Overriding and super()
A subclass can override a parent method to provide specialized behavior. To extend rather than replace the parent’s logic, use super() to invoke the original method.
class MathStudent(Student):
def choose_course(self):
super().choose_course() # Call parent's version
print("\nCourse options:\n1. Calculus\n2. Linear Algebra\n3. Probability")
# Assuming Student has a choose_course method
Linked List Example with OOP
Encapsulation also applies to data structures like linked lists, where each node contains data and a reference to the next node.
class ListNode:
def __init__(self, val=0, next_node=None):
self.val = val
self.next = next_node
def traverse(self):
current = self
while current:
print(current.val, end=", ")
current = current.next
# Helper functions to build sample lists
def build_list_1():
head = ListNode(2)
head.next = ListNode(4)
head.next.next = ListNode(3)
return head
def build_list_2():
head = ListNode(5)
head.next = ListNode(6)
head.next.next = ListNode(4)
return head
This demonstrates how OOP principles—encapsulation for data hiding and inheritance for code reuse—enable modular and maintainable Python programs.