# Python 面向对象编程

# 类和对象

# 类的定义

# 基本类定义
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"你好,我是{self.name},今年{self.age}岁"

# 创建对象
person = Person("张三", 25)
print(person.greet())

# 属性和方法

# 实例属性和类属性
class Student:
    school = "Python大学"  # 类属性
    
    def __init__(self, name, grade):
        self.name = name    # 实例属性
        self.grade = grade
    
    def study(self):        # 实例方法
        return f"{self.name}正在学习"
    
    @classmethod
    def get_school(cls):    # 类方法
        return cls.school
    
    @staticmethod
    def is_workday(day):    # 静态方法
        return day.weekday() < 5

# 继承和多态

# 基类
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}说:喵喵!"

# 多态
def animal_speak(animal):
    print(animal.speak())

dog = Dog("旺财")
cat = Cat("咪咪")
animal_speak(dog)  # 旺财说:汪汪!
animal_speak(cat)  # 咪咪说:喵喵!

# 封装

# 私有属性和方法
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # 私有属性
    
    def __validate_amount(self, amount):  # 私有方法
        return amount > 0
    
    def deposit(self, amount):
        if self.__validate_amount(amount):
            self.__balance += amount
            return True
        return False
    
    def get_balance(self):
        return self.__balance

# 特殊方法

# 魔术方法
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __len__(self):
        return 2
    
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

# 属性装饰器

# @property装饰器
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
    
    @property
    def celsius(self):
        return self._celsius
    
    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("温度不能低于绝对零度")
        self._celsius = value
    
    @property
    def fahrenheit(self):
        return self._celsius * 9/5 + 32

# 抽象类

# 抽象基类
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)

# 最佳实践

  1. 类的设计

    • 遵循单一职责原则
    • 使用合适的继承层次
    • 避免过深的继承树
  2. 封装

    • 合理使用私有属性和方法
    • 提供必要的访问接口
    • 保护对象的内部状态
  3. 继承和组合

    • 优先使用组合而非继承
    • 正确使用抽象基类
    • 避免多重继承的复杂性
  4. 代码重用

    • 使用Mixin类
    • 利用装饰器模式
    • 合理使用类方法和静态方法

# 练习题

  1. 实现一个简单的银行账户系统
  2. 设计一个图形类层次结构
  3. 创建一个带有属性验证的用户类

# 下一步

学习Python的高级特性,如元类、描述符和上下文管理器等。