面向对象编程(OOP)是一种将代码组织为包含数据和行为的对象的编程范式。Python是一种多范式语言,完全支持OOP原则:
class Dog:
# 类属性
species = "Canis familiaris"
# 构造方法
def __init__(self, name, age):
# 实例属性
self.name = name
self.age = age
# 实例方法
def bark(self):
return f"{self.name} 说汪汪!"
# 创建实例
buddy = Dog("Buddy", 5)
max = Dog("Max", 3)
print(buddy.bark()) # 输出: Buddy 说汪汪!
print(max.species) # 输出: Canis familiaris
class Counter:
# 类属性
total_counters = 0
def __init__(self):
# 实例属性
self.count = 0
Counter.total_counters += 1
def increment(self):
self.count += 1
# 创建实例
counter1 = Counter()
counter2 = Counter()
print(Counter.total_counters) # 输出: 2
print(counter1.count) # 输出: 0
counter1.increment()
print(counter1.count) # 输出: 1
print(counter2.count) # 输出: 0
class DateUtil:
def __init__(self, date):
self.date = date
# 实例方法
def add_days(self, days):
return self.date + timedelta(days=days)
# 类方法
@classmethod
def from_string(cls, date_str):
# 将字符串转换为日期并创建实例
date_obj = datetime.strptime(date_str, "%Y-%m-%d").date()
return cls(date_obj)
# 静态方法
@staticmethod
def is_valid_date(date_str):
try:
datetime.strptime(date_str, "%Y-%m-%d")
return True
except ValueError:
return False
# 使用不同类型的方法
date_util = DateUtil.from_string("2023-01-01")
print(DateUtil.is_valid_date("2023-13-01")) # 输出: False
class Circle:
def __init__(self, radius):
self._radius = radius
# 属性getter
@property
def radius(self):
return self._radius
# 属性setter
@radius.setter
def radius(self, value):
if value <= 0:
raise ValueError("半径必须为正数")
self._radius = value
# 带计算的属性
@property
def area(self):
return 3.14159 * self._radius ** 2
# 使用属性
circle = Circle(5)
print(circle.radius) # 输出: 5
print(circle.area) # 输出: 78.53975
circle.radius = 10 # 使用setter
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} 说汪汪!"
class Cat(Animal):
def speak(self):
return f"{self.name} 说喵喵!"
# 使用继承类
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # 输出: Buddy 说汪汪!
print(cat.speak()) # 输出: Whiskers 说喵喵!
class Flyable:
def fly(self):
return "我会飞!"
class Swimmable:
def swim(self):
return "我会游泳!"
class Duck(Animal, Flyable, Swimmable):
def speak(self):
return f"{self.name} 说嘎嘎!"
# 使用多重继承
duck = Duck("Donald")
print(duck.speak()) # 输出: Donald 说嘎嘎!
print(duck.fly()) # 输出: 我会飞!
print(duck.swim()) # 输出: 我会游泳!
class A:
def method(self):
return "A"
class B(A):
def method(self):
return "B" + super().method()
class C(A):
def method(self):
return "C" + super().method()
class D(B, C):
def method(self):
return "D" + super().method()
# 理解MRO
d = D()
print(d.method()) # 输出: DBCA
print(D.__mro__) # 显示方法解析顺序
from dataclasses import dataclass
from typing import List
@dataclass
class Point:
x: float
y: float
def distance_from_origin(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
# 使用数据类
point = Point(3, 4)
print(point) # 输出: Point(x=3, y=4)
print(point.distance_from_origin()) # 输出: 5.0
from dataclasses import dataclass, field
@dataclass
class Student:
name: str
grades: List[int] = field(default_factory=list)
average: float = field(init=False)
def __post_init__(self):
self.average = sum(self.grades) / len(self.grades) if self.grades else 0
# 使用数据类高级特性
student = Student("Alice", [90, 85, 95])
print(student.average) # 输出: 90.0
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)
# 使用抽象类
rect = Rectangle(5, 3)
print(rect.area()) # 输出: 15
print(rect.perimeter()) # 输出: 16
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
# 使用上下文管理器
with FileManager("test.txt", "w") as f:
f.write("Hello, World!")
class BankAccount:
def __init__(self, account_number: str, owner: str, balance: float = 0):
self._account_number = account_number
self._owner = owner
self._balance = balance
self._transactions = []
@property
def balance(self):
return self._balance
def deposit(self, amount: float):
if amount <= 0:
raise ValueError("存款金额必须为正数")
self._balance += amount
self._transactions.append(("deposit", amount))
return self._balance
def withdraw(self, amount: float):
if amount <= 0:
raise ValueError("取款金额必须为正数")
if amount > self._balance:
raise ValueError("余额不足")
self._balance -= amount
self._transactions.append(("withdrawal", amount))
return self._balance
def get_transaction_history(self):
return self._transactions
class SavingsAccount(BankAccount):
def __init__(self, account_number: str, owner: str, interest_rate: float):
super().__init__(account_number, owner)
self.interest_rate = interest_rate
def add_interest(self):
interest = self._balance * self.interest_rate
self.deposit(interest)
return interest
# 使用银行账户系统
account = SavingsAccount("123456", "John Doe", 0.05)
account.deposit(1000)
account.withdraw(200)
account.add_interest()
print(account.balance)
print(account.get_transaction_history())
from typing import Any, List
from collections.abc import Sequence
class SortedList(Sequence):
def __init__(self, items: List[Any] = None):
self._items = sorted(items) if items else []
def __len__(self):
return len(self._items)
def __getitem__(self, index):
return self._items[index]
def add(self, item):
from bisect import insort
insort(self._items, item)
def remove(self, item):
self._items.remove(item)
def __repr__(self):
return f"SortedList({self._items})"
# 使用自定义集合
sorted_list = SortedList([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
print(sorted_list) # 输出: SortedList([1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9])
sorted_list.add(7)
print(sorted_list) # 输出: SortedList([1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 7, 9])
from abc import ABC, abstractmethod
from typing import Dict, Type
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "汪汪!"
class Cat(Animal):
def speak(self):
return "喵喵!"
class AnimalFactory:
_animals: Dict[str, Type[Animal]] = {
"dog": Dog,
"cat": Cat
}
@classmethod
def create_animal(cls, animal_type: str) -> Animal:
animal_class = cls._animals.get(animal_type.lower())
if not animal_class:
raise ValueError(f"未知动物类型: {animal_type}")
return animal_class()
@classmethod
def register_animal(cls, animal_type: str, animal_class: Type[Animal]):
cls._animals[animal_type.lower()] = animal_class
# 使用工厂模式
dog = AnimalFactory.create_animal("dog")
cat = AnimalFactory.create_animal("cat")
print(dog.speak()) # 输出: 汪汪!
print(cat.speak()) # 输出: 喵喵!
本教程涵盖了Python类、继承和数据方法的基础与高级概念。通过修改示例和编写自己的类来练习这些概念。记住,面向对象编程是组织和结构化代码、提高可维护性和复用性的强大范式。