Python面向对象编程(OOP)详解
一、类与对象基础
面向对象编程的核心是类和对象的概念...
1. 类定义与实例化
class Dog:
# 类属性
species = "哺乳动物"
# 构造方法
def __init__(self, name, age):
# 实例属性
self.name = name
self.age = age
# 实例方法
def bark(self):
print(f"{self.name}说: 汪汪!")
# 创建对象
my_dog = Dog("旺财", 3)
my_dog.bark() # 输出: 旺财说: 汪汪!
二、面向对象四大支柱
面向对象编程基于四个核心概念...
| 概念 | 说明 | Python实现 |
|---|---|---|
| 封装 | 隐藏内部实现细节 | 私有属性/方法(_前缀) |
| 继承 | 子类继承父类特性 | class Child(Parent): |
| 多态 | 不同对象对相同方法的不同实现 | 方法重写 |
| 抽象 | 定义接口规范 | abc模块 |
1. 继承示例
class Animal:
def speak(self):
pass
class Cat(Animal):
def speak(self):
print("喵喵~")
class Dog(Animal):
def speak(self):
print("汪汪!")
# 多态表现
animals = [Cat(), Dog()]
for animal in animals:
animal.speak() # 不同对象表现不同
三、高级OOP特性
Python支持多种面向对象高级特性...
1. 类方法与静态方法
class MyClass:
@classmethod
def class_method(cls):
print(f"调用类方法,类名: {cls.__name__}")
@staticmethod
def static_method():
print("调用静态方法,无需类或实例引用")
# 调用方法
MyClass.class_method()
MyClass.static_method()
2. 属性装饰器
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:
self._radius = value
else:
raise ValueError("半径必须为正数")
@property
def area(self):
return 3.14 * self._radius ** 2
# 使用属性
c = Circle(5)
print(c.area) # 输出: 78.5
c.radius = 10 # 使用setter方法
四、特殊方法与操作符重载
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 __repr__(self):
return f"Vector({self.x}, {self.y})"
# 使用重载操作符
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2 # 使用__add__
print(v3) # 使用__str__: Vector(6, 8)
五、设计模式实践
常见设计模式在Python中的实现...
1. 单例模式
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
# 测试单例
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # 输出: True
2. 工厂模式
class ShapeFactory:
def create_shape(self, shape_type):
if shape_type == "circle":
return Circle()
elif shape_type == "rectangle":
return Rectangle()
else:
raise ValueError("不支持的形状类型")
# 使用工厂
factory = ShapeFactory()
circle = factory.create_shape("circle")
返回首页