Python 面向对象编程详解
类与对象的基本概念
类(Class)
类是创建对象的模板,定义了对象的属性和方法。类是抽象的,不占用内存。
对象(Object)
对象是类的实例,占用内存,具有具体的属性值。
pythonclass Person: def __init__(self, name, age): self.name = name # 实例属性 self.age = age def say_hello(self): # 实例方法 print(f"Hello, I'm {self.name}, {self.age} years old") # 创建对象 person1 = Person("Alice", 25) person2 = Person("Bob", 30) person1.say_hello() # Hello, I'm Alice, 25 years old person2.say_hello() # Hello, I'm Bob, 30 years old
类属性与实例属性
类属性
类属性属于类本身,所有实例共享同一个类属性。
pythonclass Dog: species = "Canis familiaris" # 类属性 count = 0 # 类属性 def __init__(self, name): self.name = name # 实例属性 Dog.count += 1 dog1 = Dog("Buddy") dog2 = Dog("Max") print(dog1.species) # Canis familiaris print(dog2.species) # Canis familiaris print(Dog.count) # 2 # 修改类属性 Dog.species = "Canis lupus" print(dog1.species) # Canis lupus print(dog2.species) # Canis lupus
实例属性
实例属性属于单个对象实例,每个实例有自己独立的副本。
pythonclass Car: def __init__(self, brand, color): self.brand = brand # 实例属性 self.color = color # 实例属性 car1 = Car("Toyota", "Red") car2 = Car("Honda", "Blue") print(car1.brand) # Toyota print(car2.brand) # Honda # 修改实例属性 car1.color = "Green" print(car1.color) # Green print(car2.color) # Blue
方法类型
实例方法
实例方法是最常用的方法,第一个参数是 self,表示对象本身。
pythonclass Circle: def __init__(self, radius): self.radius = radius def area(self): # 实例方法 return 3.14159 * self.radius ** 2 def circumference(self): # 实例方法 return 2 * 3.14159 * self.radius circle = Circle(5) print(circle.area()) # 78.53975 print(circle.circumference()) # 31.4159
类方法
类方法使用 @classmethod 装饰器,第一个参数是 cls,表示类本身。
pythonclass Person: count = 0 def __init__(self, name): self.name = name Person.count += 1 @classmethod def get_count(cls): # 类方法 return cls.count @classmethod def create_from_string(cls, name_str): # 类方法作为工厂方法 name = name_str.strip().title() return cls(name) person1 = Person("Alice") person2 = Person.create_from_string(" bob ") print(Person.get_count()) # 2 print(person2.name) # Bob
静态方法
静态方法使用 @staticmethod 装饰器,不需要 self 或 cls 参数。
pythonclass MathUtils: @staticmethod def add(a, b): # 静态方法 return a + b @staticmethod def multiply(a, b): # 静态方法 return a * b # 直接通过类调用 print(MathUtils.add(3, 5)) # 8 print(MathUtils.multiply(4, 6)) # 24 # 也可以通过对象调用 math_utils = MathUtils() print(math_utils.add(3, 5)) # 8
继承
单继承
pythonclass Animal: def __init__(self, name): self.name = name def speak(self): pass class Dog(Animal): # 继承 Animal 类 def speak(self): return f"{self.name} says Woof!" class Cat(Animal): # 继承 Animal 类 def speak(self): return f"{self.name} says Meow!" dog = Dog("Buddy") cat = Cat("Whiskers") print(dog.speak()) # Buddy says Woof! print(cat.speak()) # Whiskers says Meow!
多继承
pythonclass Flyable: def fly(self): return "Flying" class Swimmable: def swim(self): return "Swimming" class Duck(Flyable, Swimmable): # 多继承 def __init__(self, name): self.name = name def quack(self): return f"{self.name} says Quack!" duck = Duck("Donald") print(duck.fly()) # Flying print(duck.swim()) # Swimming print(duck.quack()) # Donald says Quack!
方法解析顺序(MRO)
pythonclass A: def method(self): print("A") class B(A): def method(self): print("B") class C(A): def method(self): print("C") class D(B, C): # 多继承 pass d = D() d.method() # B # 查看 MRO print(D.__mro__) # (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
多态
多态允许不同类的对象对同一消息做出不同的响应。
pythonclass Shape: def area(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14159 * self.radius ** 2 def calculate_area(shape): return shape.area() # 多态:不同对象调用相同方法 rectangle = Rectangle(5, 3) circle = Circle(4) print(calculate_area(rectangle)) # 15 print(calculate_area(circle)) # 50.26544
封装
封装是将数据和操作数据的方法绑定在一起,并隐藏内部实现细节。
私有属性和方法
pythonclass BankAccount: def __init__(self, account_number, balance): self.account_number = account_number self.__balance = balance # 私有属性(双下划线) def deposit(self, amount): if amount > 0: self.__balance += amount return True return False def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount return True return False def get_balance(self): # 访问私有属性 return self.__balance def __validate_amount(self, amount): # 私有方法 return amount > 0 account = BankAccount("123456", 1000) account.deposit(500) account.withdraw(200) print(account.get_balance()) # 1300 # 无法直接访问私有属性 # print(account.__balance) # AttributeError
属性装饰器
pythonclass Temperature: def __init__(self, celsius): self.__celsius = celsius @property def celsius(self): # getter return self.__celsius @celsius.setter def celsius(self, value): # setter if value < -273.15: raise ValueError("Temperature below absolute zero") self.__celsius = value @property def fahrenheit(self): # 只读属性 return self.__celsius * 9/5 + 32 temp = Temperature(25) print(temp.celsius) # 25 print(temp.fahrenheit) # 77.0 temp.celsius = 30 print(temp.celsius) # 30 # temp.celsius = -300 # ValueError
抽象类与接口
抽象基类(ABC)
pythonfrom abc import ABC, abstractmethod class Animal(ABC): # 抽象基类 @abstractmethod def speak(self): # 抽象方法 pass @abstractmethod def move(self): # 抽象方法 pass class Dog(Animal): def speak(self): return "Woof!" def move(self): return "Running" class Cat(Animal): def speak(self): return "Meow!" def move(self): return "Prowling" # 无法直接实例化抽象类 # animal = Animal() # TypeError dog = Dog() cat = Cat() print(dog.speak()) # Woof! print(cat.move()) # Prowling
特殊方法(魔术方法)
常用特殊方法
pythonclass Vector: def __init__(self, x, y): self.x = x self.y = y def __str__(self): # 字符串表示 return f"Vector({self.x}, {self.y})" def __repr__(self): # 开发者表示 return f"Vector(x={self.x}, y={self.y})" def __add__(self, other): # 加法运算 return Vector(self.x + other.x, self.y + other.y) def __eq__(self, other): # 相等比较 return self.x == other.x and self.y == other.y def __len__(self): # 长度 return int((self.x ** 2 + self.y ** 2) ** 0.5) v1 = Vector(3, 4) v2 = Vector(1, 2) print(v1) # Vector(3, 4) print(repr(v1)) # Vector(x=3, y=4) print(v1 + v2) # Vector(4, 6) print(v1 == Vector(3, 4)) # True print(len(v1)) # 5
上下文管理器
pythonclass 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() return False # 使用上下文管理器 with FileManager("example.txt", "w") as f: f.write("Hello, World!") # 文件自动关闭
设计模式
单例模式
pythonclass Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance s1 = Singleton() s2 = Singleton() print(s1 is s2) # True
工厂模式
pythonfrom abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def speak(self): pass class Dog(Animal): def speak(self): return "Woof!" class Cat(Animal): def speak(self): return "Meow!" class AnimalFactory: @staticmethod def create_animal(animal_type): if animal_type == "dog": return Dog() elif animal_type == "cat": return Cat() else: raise ValueError(f"Unknown animal type: {animal_type}") dog = AnimalFactory.create_animal("dog") cat = AnimalFactory.create_animal("cat") print(dog.speak()) # Woof! print(cat.speak()) # Meow!
最佳实践
1. 使用组合优于继承
python# 不好的做法 - 过度使用继承 class FlyingDog(Dog, Flyable): pass # 好的做法 - 使用组合 class Robot: def __init__(self, flying_ability): self.flying_ability = flying_ability def fly(self): return self.flying_ability.fly() class FlyingAbility: def fly(self): return "Flying" robot = Robot(FlyingAbility()) print(robot.fly()) # Flying
2. 遵循 SOLID 原则
python# 单一职责原则 class User: def __init__(self, name, email): self.name = name self.email = email class UserRepository: def save(self, user): pass class EmailService: def send_email(self, user, message): pass
3. 使用类型提示
pythonfrom typing import List, Optional class Product: def __init__(self, name: str, price: float): self.name = name self.price = price def get_discounted_price(self, discount: float) -> float: return self.price * (1 - discount) class ShoppingCart: def __init__(self): self.items: List[Product] = [] def add_item(self, product: Product) -> None: self.items.append(product) def get_total(self) -> float: return sum(item.price for item in self.items)
总结
Python 面向对象编程的核心概念:
- 类与对象:类是模板,对象是实例
- 属性与方法:类属性共享,实例属性独立;实例方法、类方法、静态方法
- 继承:单继承、多继承、方法解析顺序(MRO)
- 多态:不同对象对同一消息的不同响应
- 封装:隐藏内部实现,提供公共接口
- 抽象类:定义接口规范,强制子类实现
- 特殊方法:实现运算符重载、上下文管理等
- 设计模式:单例、工厂等常用模式
掌握面向对象编程,能够编写出结构清晰、易于维护和扩展的代码。