面向对象高级编程

Python面向对象高级特性教程

面向对象编程(OOP)在Python中不仅限于基本的封装、继承和多态概念。Python提供了一系列高级特性,使开发者能够构建更灵活、更强大的程序。本文将介绍Python中的多重继承、定制类和元类等高级OOP特性。

多重继承

基本概念

多重继承允许一个类从多个父类继承属性和方法:

class Father:
    def father_method(self):
        print("Father's method")

class Mother:
    def mother_method(self):
        print("Mother's method")

class Child(Father, Mother):
    pass

child = Child()
child.father_method()  # 输出: Father's method
child.mother_method()  # 输出: Mother's method

方法解析顺序(MRO)

Python使用C3线性化算法来确定方法解析顺序:

print(Child.__mro__)
# 输出: (<class '__main__.Child'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class 'object'>)

最佳实践

  1. 避免"菱形继承"问题
  2. 使用super()函数调用父类方法
  3. 考虑使用组合而非多重继承

定制类

特殊方法(魔术方法)

Python允许通过实现特殊方法来定制类的行为:

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 __str__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __len__(self):
        return 2
    
    def __getitem__(self, index):
        if index == 0:
            return self.x
        elif index == 1:
            return self.y
        else:
            raise IndexError("Vector index out of range")

v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1 + v2)  # 输出: Vector(6, 8)
print(len(v1))  # 输出: 2
print(v1[0])    # 输出: 2

常用魔术方法

方法描述触发条件
__init__构造函数创建对象时
__del__析构函数对象被销毁时
__str__字符串表示str(obj)print(obj)
__repr__官方字符串表示repr(obj)
__len__长度len(obj)
__getitem__索引访问obj[key]
__setitem__索引赋值obj[key] = value
__iter__迭代器iter(obj)for x in obj
__call__使实例可调用obj()

元类

基本概念

元类是创建类的类,是Python中最深奥的OOP概念之一。

class Meta(type):
    def __new__(cls, name, bases, namespace):
        print(f"Creating class {name}")
        return super().__new__(cls, name, bases, namespace)

class MyClass(metaclass=Meta):
    pass
# 输出: Creating class MyClass

使用场景

  1. 注册所有子类
  2. 验证类属性
  3. 自动添加方法
  4. 实现ORM框架

示例:单例模式实现

class SingletonMeta(type):
    _instances = {}
    
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class Singleton(metaclass=SingletonMeta):
    pass

a = Singleton()
b = Singleton()
print(a is b)  # 输出: True

属性访问控制

描述符协议

class Descriptor:
    def __get__(self, instance, owner):
        print(f"Getting from {instance}")
        return instance._value
    
    def __set__(self, instance, value):
        print(f"Setting to {value}")
        instance._value = value
    
    def __delete__(self, instance):
        print("Deleting")
        del instance._value

class MyClass:
    attr = Descriptor()
    
    def __init__(self, value):
        self._value = value

obj = MyClass(10)
print(obj.attr)  # 输出: Getting from <__main__.MyClass object...> 然后 10
obj.attr = 20    # 输出: Setting to 20

property装饰器

class Circle:
    def __init__(self, radius):
        self._radius = radius
    
    @property
    def radius(self):
        return self._radius
    
    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("Radius cannot be negative")
        self._radius = value
    
    @radius.deleter
    def radius(self):
        print("Deleting radius")
        del self._radius

c = Circle(5)
print(c.radius)  # 输出: 5
c.radius = 10
del c.radius     # 输出: Deleting radius

抽象基类(ABC)

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)

# shape = Shape()  # 会报错,不能实例化抽象类
rect = Rectangle(3, 4)
print(rect.area())  # 输出: 12

总结

Python的面向对象高级特性提供了极大的灵活性:

  1. 多重继承:允许从多个父类继承,但需谨慎使用
  2. 定制类:通过魔术方法可以自定义类的各种行为
  3. 元类:控制类的创建过程,实现高级模式
  4. 属性控制:通过描述符和property精细控制属性访问
  5. 抽象基类:定义接口规范,强制子类实现特定方法

这些高级特性使得Python能够支持各种复杂的设计模式,构建灵活且强大的应用程序架构。