文章目录
1. 基本概念
在Python编程中,对象(Object)和类(Class)是面向对象编程(OOP)的核心概念。理解这两个概念有助于我们更好地组织代码,并提高代码的可重用性和可维护性。
1.1 类(Class)
类是一个模板或蓝图,用于定义对象的属性和行为。类定义了一组属性和方法,这些属性和方法是对象所共有的。可以将类看作是一种数据类型,就像字符串、整数等内置数据类型一样,但类是由用户定义的。
- 定义一个类
在Python中,使用class
关键字来定义一个类。类的名称通常采用大写字母开头的驼峰命名法。
class Dog:
pass # 使用pass语句创建一个空类
- 1
- 2
上面的代码定义了一个名为Dog
的类,但这个类目前没有任何属性或方法。
1.2 对象(Object)
对象是类的实例。一个类可以有多个实例,每个实例都有独立的属性。对象是类的具体体现,通过类创建的对象可以使用类定义的属性和方法。
- 创建一个对象
my_dog = Dog() # 创建Dog类的一个实例
- 1
在上面的代码中,my_dog
是Dog
类的一个实例(对象)。
2. 类的属性和方法
类可以包含属性(数据)和方法(函数)。属性是类的变量,用于存储对象的状态,而方法是类的函数,用于定义对象的行为。
- 定义类的属性和方法
class Dog:
# 类的属性
species = "Canis familiaris"
# 初始化方法,用于初始化实例的属性
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 类的方法
def bark(self):
return f"{self.name} says woof!"
# 创建一个Dog类的实例
my_dog = Dog("Buddy", 3)
# 访问实例属性
print(my_dog.name) # 输出: Buddy
print(my_dog.age) # 输出: 3
# 调用实例方法
print(my_dog.bark()) # 输出: Buddy says woof!
# 访问类属性
print(Dog.species) # 输出: Canis familiaris
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
在这个示例中:
species
是一个类属性,所有Dog
类的实例共享这个属性。name
和age
是实例属性,每个实例都有独立的这些属性。__init__
方法是初始化方法,在创建实例时被调用,用于初始化实例的属性。bark
是一个实例方法,可以通过实例来调用。
3. 类的继承
3.1 继承的概念
继承是面向对象编程的一个重要特性,它允许一个类(子类或派生类)继承另一个类(父类或基类)的属性和方法。通过继承,子类可以重用父类的代码,同时可以扩展或修改父类的行为。
继承的主要优点包括:
- 代码重用:子类可以直接使用父类中已经定义的属性和方法,避免重复代码。
- 扩展功能:子类可以增加新的属性和方法,扩展父类的功能。
- 多态性:子类可以重写父类的方法,提供特定的实现。
3.2 单继承
在Python中,单继承指的是一个子类继承一个父类。子类可以通过在类定义中指定父类的方式来继承父类。
示例:定义一个父类和一个子类
# 定义一个父类
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
# 定义一个子类,继承自Animal类
class Dog(Animal):
def speak(self):
return f"{self.name} says woof!"
# 创建父类和子类的实例
generic_animal = Animal("Animal")
dog = Dog("Buddy")
# 调用方法
print(generic_animal.speak()) # 输出: Animal makes a sound.
print(dog.speak()) # 输出: Buddy says woof!
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
在这个示例中:
Animal
是父类,定义了__init__
方法和speak
方法。Dog
是子类,通过在类定义中括号内指定父类Animal
来实现继承。- 子类
Dog
重写了父类的speak
方法。
3.3 多重继承
多重继承指的是一个子类可以继承多个父类。Python支持多重继承,但需要谨慎使用,因为它可能导致复杂的继承关系和潜在的冲突。
- 示例:多重继承
# 定义两个父类
class Canine:
def __init__(self):
self.has_tail = True
def wag_tail(self):
return "Wagging tail."
class Pet:
def __init__(self, name):
self.name = name
def play(self):
return f"{self.name} is playing."
# 定义一个子类,继承自Canine和Pet
class Dog(Canine, Pet):
def __init__(self, name):
Canine.__init__(self)
Pet.__init__(self, name)
# 创建子类的实例
dog = Dog("Buddy")
# 访问继承的属性和方法
print(dog.has_tail) # 输出: True
print(dog.wag_tail()) # 输出: Wagging tail.
print(dog.play()) # 输出: Buddy is playing.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
在这个示例中:
Canine
和Pet
是两个父类。Dog
是一个子类,通过在类定义中括号内指定多个父类实现多重继承。- 子类
Dog
在其构造函数中显式调用了两个父类的构造函数,以初始化父类的属性。
4. 方法重写与多态
4.1 方法重写
方法重写(Method Overriding)是指在子类中定义一个与父类具有相同名称的方法,从而取代父类中的方法实现。当子类的实例调用这个方法时,将执行子类中的版本,而不是父类中的版本。
- 示例:方法重写
# 定义父类
class Animal:
def speak(self):
return "Animal makes a sound."
# 定义子类,重写父类的方法
class Dog(Animal):
def speak(self):
return "Dog says woof!"
# 创建父类和子类的实例
generic_animal = Animal()
dog = Dog()
# 调用方法
print(generic_animal.speak()) # 输出: Animal makes a sound.
print(dog.speak()) # 输出: Dog says woof!
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
在这个示例中:
Animal
类定义了一个speak
方法。Dog
类继承自Animal
,并重写了speak
方法。- 当调用
dog.speak()
时,执行的是Dog
类中的speak
方法。
4.2 多态
多态(Polymorphism)是一种面向对象编程的特性,允许使用不同的类的对象来调用相同的方法。不同的对象在调用相同的方法时,表现出不同的行为。多态性通常通过继承和方法重写来实现。
- 示例:多态
# 定义父类
class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
# 定义子类
class Dog(Animal):
def speak(self):
return "Dog says woof!"
class Cat(Animal):
def speak(self):
return "Cat says meow!"
# 定义一个函数,接受Animal类型的对象
def make_animal_speak(animal):
print(animal.speak())
# 创建不同类型的Animal对象
dog = Dog()
cat = Cat()
# 调用函数,实现多态
make_animal_speak(dog) # 输出: Dog says woof!
make_animal_speak(cat) # 输出: Cat says meow!
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
在这个示例中:
Animal
类定义了一个抽象的speak
方法,要求所有子类实现这个方法。Dog
和Cat
类分别继承自Animal
,并实现了各自的speak
方法。make_animal_speak
函数接受一个Animal
类型的对象,并调用它的speak
方法。- 通过传递不同类型的
Animal
对象(Dog
和Cat
),函数调用表现出不同的行为,实现了多态。
多态的优势
-
代码灵活性:可以编写更加灵活和可扩展的代码。
-
代码重用:通过继承和方法重写,可以减少代码重复,提高代码重用性。
-
接口一致性:多态性使得可以使用统一的接口来处理不同类型的对象,简化代码。
-
示例:多态在实际应用中的使用
# 定义基类
class Shape:
def area(self):
raise NotImplementedError("Subclass must implement abstract method")
# 定义子类
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
# 定义一个函数,接受Shape类型的对象
def print_area(shape):
print(f"The area is {shape.area()}")
# 创建不同类型的Shape对象
circle = Circle(5)
square = Square(4)
# 调用函数,实现多态
print_area(circle) # 输出: The area is 78.5
print_area(square) # 输出: The area is 16
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
在这个示例中:
Shape
类定义了一个抽象的area
方法。Circle
和Square
类分别继承自Shape
,并实现了各自的area
方法。print_area
函数接受一个Shape
类型的对象,并调用它的area
方法。- 通过传递不同类型的
Shape
对象(Circle
和Square
),函数调用表现出不同的行为,实现了多态。
5. 特殊方法与运算符重载
5.1 特殊方法(魔法方法)
特殊方法(也称为魔法方法)是Python中具有特殊名称的方法,它们是通过双下划线包围的。特殊方法允许类定义特定的行为,如初始化对象、表示对象、比较对象等。以下是一些常用的特殊方法:
5.1.1 __init__
方法
__init__
方法是一个构造函数,在创建对象时自动调用,用于初始化对象的属性。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(p.name) # 输出: Alice
print(p.age) # 输出: 30
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
5.1.2 __str__
方法
__str__
方法定义了对象的字符串表示,在使用 print
函数或 str()
函数时调用。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
p = Person("Alice", 30)
print(p) # 输出: Person(name=Alice, age=30)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
5.1.3 __repr__
方法
__repr__
方法定义了对象的官方字符串表示,通常用于调试。在使用 repr()
函数或交互解释器中直接输入对象时调用。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
p = Person("Alice", 30)
print(repr(p)) # 输出: Person(name=Alice, age=30)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
5.1.4 __len__
方法
__len__
方法定义了对象的长度,在使用 len()
函数时调用。
class MyList:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
my_list = MyList([1, 2, 3, 4])
print(len(my_list)) # 输出: 4
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
5.1.5 __eq__
方法
__eq__
方法定义了对象的相等性比较,在使用 ==
运算符时调用。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
if isinstance(other, Person):
return self.name == other.name and self.age == other.age
return False
p1 = Person("Alice", 30)
p2 = Person("Alice", 30)
p3 = Person("Bob", 25)
print(p1 == p2) # 输出: True
print(p1 == p3) # 输出: False
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
5.2 运算符重载
运算符重载(Operator Overloading)允许我们定义或重定义类的运算符行为。通过重载运算符,可以实现自定义的运算符行为,使类的实例能够参与各种运算。
- 示例:重载加法运算符 (
+
)
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Vector):
return Vector(self.x + other.x, self.y + other.y)
return NotImplemented
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(5, 7)
v3 = v1 + v2
print(v3) # 输出: Vector(7, 10)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
在这个示例中:
-
__add__
方法重载了加法运算符,使得两个Vector
对象可以相加。 -
__repr__
方法用于提供对象的字符串表示,便于调试和打印输出。 -
示例:重载其他运算符
除了加法运算符 (+
),我们还可以重载其他运算符,如减法运算符 (-
)、乘法运算符 (*
)、除法运算符 (/
)、比较运算符 (<
, >
, <=
, >=
) 等。
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, other):
if isinstance(other, Vector):
return Vector(self.x - other.x, self.y - other.y)
return NotImplemented
def __mul__(self, scalar):
if isinstance(scalar, (int, float)):
return Vector(self.x * scalar, self.y * scalar)
return NotImplemented
def __lt__(self, other):
if isinstance(other, Vector):
return (self.x**2 + self.y**2) < (other.x**2 + other.y**2)
return NotImplemented
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(5, 7)
print(v1 - v2) # 输出: Vector(-3, -4)
print(v1 * 3) # 输出: Vector(6, 9)
print(v1 < v2) # 输出: True
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
在这个示例中:
__sub__
方法重载了减法运算符 (-
),使得两个Vector
对象可以相减。__mul__
方法重载了乘法运算符 (*
),使得Vector
对象可以与标量相乘。__lt__
方法重载了小于运算符 (<
),使得可以比较两个Vector
对象的大小。
6. 静态方法与类方法
6.1 静态方法
静态方法是类中定义的方法,但它不依赖于类的实例或类本身的属性。它类似于普通函数,只是定义在类的命名空间中。静态方法可以通过类名直接调用,也可以通过类的实例调用。通常用于定义逻辑上属于类但不需要访问类或实例属性的方法。
- 定义和使用静态方法
在Python中,使用@staticmethod
装饰器定义静态方法。
class MathOperations:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def multiply(a, b):
return a * b
# 通过类名调用静态方法
print(MathOperations.add(3, 5)) # 输出: 8
print(MathOperations.multiply(3, 5)) # 输出: 15
# 通过实例调用静态方法
math_ops = MathOperations()
print(math_ops.add(10, 20)) # 输出: 30
print(math_ops.multiply(10, 20)) # 输出: 200
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
在这个示例中:
add
和multiply
是静态方法,不访问类的任何属性或实例属性。- 静态方法可以通过类名或类的实例调用。
6.2 类方法
类方法是类中定义的方法,使用@classmethod
装饰器定义。类方法的第一个参数是类本身,通常命名为cls
。类方法可以访问类属性和调用其他类方法,但不能直接访问实例属性。
- 定义和使用类方法
在Python中,使用@classmethod
装饰器定义类方法。
class Person:
population = 0 # 类属性
def __init__(self, name):
self.name = name
Person.population += 1
@classmethod
def get_population(cls):
return cls.population
@classmethod
def create_person(cls, name):
return cls(name)
# 创建实例
p1 = Person("Alice")
p2 = Person("Bob")
# 通过类名调用类方法
print(Person.get_population()) # 输出: 2
# 使用类方法创建实例
p3 = Person.create_person("Charlie")
print(p3.name) # 输出: Charlie
# 再次调用类方法获取更新后的人口数量
print(Person.get_population()) # 输出: 3
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
在这个示例中:
get_population
是一个类方法,返回当前人口数量(类属性population
)。create_person
是一个类方法,用于创建新的Person
实例。- 类方法可以通过类名或类的实例调用。
6.3 静态方法与类方法的对比
特性 | 静态方法 | 类方法 |
---|---|---|
定义装饰器 | @staticmethod | @classmethod |
第一个参数 | 无特殊参数 | cls (指向类本身) |
访问类属性 | 不能 | 可以 |
访问实例属性 | 不能 | 不能 |
调用方式 | 通过类名或实例调用 | 通过类名或实例调用 |
静态方法和类方法各有用途,选择使用哪种方法取决于具体需求:
- 使用静态方法来定义与类关联的函数,但不需要访问类或实例属性。
- 使用类方法来操作类属性或调用其他类方法。
7. 属性装饰器
属性装饰器@property
是Python中一个非常有用的功能,它允许你将类的方法转换为属性,从而实现更简洁和更易读的代码。使用@property
装饰器可以定义只读属性和可读写属性。
7.1 定义只读属性
只读属性是指只能获取其值而不能修改其值的属性。通过使用@property
装饰器,可以将一个方法定义为只读属性。
- 示例:定义只读属性
class Circle:
def __init__(self, radius):
self._radius = radius # 保护属性
@property
def radius(self):
return self._radius
@property
def area(self):
return 3.14 * self._radius ** 2
# 创建实例
circle = Circle(5)
# 访问只读属性
print(circle.radius) # 输出: 5
print(circle.area) # 输出: 78.5
# 尝试修改只读属性会引发错误
# circle.radius = 10 # AttributeError: can't set attribute
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
在这个示例中:
radius
和area
属性使用@property
装饰器定义为只读属性。- 可以通过实例访问这些属性,但不能修改它们。
7.2 定义可读写属性
要定义可读写属性,需要同时定义getter和setter方法。使用@property
装饰器定义getter方法,并使用@<属性名>.setter
装饰器定义setter方法。
- 示例:定义可读写属性
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("Radius must be positive")
@property
def area(self):
return 3.14 * self._radius ** 2
# 创建实例
circle = Circle(5)
# 访问可读写属性
print(circle.radius) # 输出: 5
# 修改可读写属性
circle.radius = 10
print(circle.radius) # 输出: 10
print(circle.area) # 输出: 314.0
# 尝试设置非法值会引发错误
# circle.radius = -5 # ValueError: Radius must be positive
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
在这个示例中:
radius
属性有getter和setter方法,使用@property
和@radius.setter
装饰器定义。area
属性仍然是只读属性,使用@property
装饰器定义。- 通过setter方法,可以对
radius
属性进行合法性检查,确保其值为正数。
7.3 只读属性与可读写属性对比
特性 | 只读属性 | 可读写属性 |
---|---|---|
Getter方法 | 使用@property 装饰器定义 | 使用@property 装饰器定义 |
Setter方法 | 不定义Setter方法 | 使用@<属性名>.setter 装饰器定义 |
可修改性 | 属性值不能被修改 | 属性值可以被修改并可以进行合法性检查 |
使用场景 | 属性值一旦设定后不应被改变的情况 | 属性值需要动态调整并可能需要验证的情况 |
通过使用@property
装饰器,我们可以将类的方法转换为属性,从而实现更简洁和更易读的代码。属性装饰器不仅提高了代码的可读性,还提供了对属性值的更精细的控制。
8. 面向对象设计原则与模式
8.1 设计的五大基本原则
SOLID原则是面向对象设计的五大基本原则,它们有助于创建更灵活、可维护和可扩展的代码。
8.1.1 单一职责原则(Single Responsibility Principle,SRP)
每个类应该只有一个单一的职责,即一个类只负责一件事情。这使得类更容易理解、维护和修改。
- 示例:
class Report:
def __init__(self, data):
self.data = data
def generate_report(self):
# 生成报告
pass
class ReportPrinter:
def print_report(self, report):
# 打印报告
pass
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
在这个示例中,Report
类只负责生成报告,而ReportPrinter
类负责打印报告。
8.1.2 开放封闭原则(Open/Closed Principle,OCP)
软件实体(类、模块、函数等)应该对扩展开放,对修改封闭。这意味着可以扩展一个类的行为,而无需修改其源代码。
- 示例:
class 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.14 * self.radius ** 2
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
在这个示例中,Shape
类可以通过扩展子类来增加新形状,而无需修改现有类的代码。
8.1.3 里氏替换原则(Liskov Substitution Principle,LSP)
子类对象应该可以替换父类对象,并且程序的行为不会改变。这意味着子类必须能够替代父类,且不改变程序的正确性。
- 示例:
class Bird:
def fly(self):
pass
class Sparrow(Bird):
def fly(self):
return "Sparrow flying"
class Ostrich(Bird):
def fly(self):
raise NotImplementedError("Ostriches cannot fly")
def make_bird_fly(bird):
print(bird.fly())
sparrow = Sparrow()
ostrich = Ostrich()
make_bird_fly(sparrow) # 输出: Sparrow flying
make_bird_fly(ostrich) # 抛出NotImplementedError
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
在这个示例中,Ostrich
类违反了里氏替换原则,因为它不能飞翔。
8.1.4 接口隔离原则(Interface Segregation Principle,ISP)
客户端不应该被迫依赖它不使用的方法。应将胖接口拆分为更小、更具体的接口,这样客户端将只需知道它们感兴趣的方法。
- 示例:
class Printer:
def print(self):
pass
class Scanner:
def scan(self):
pass
class MultiFunctionDevice(Printer, Scanner):
def print(self):
return "Printing..."
def scan(self):
return "Scanning..."
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
在这个示例中,Printer
和Scanner
接口被分离,客户端只需依赖他们需要的方法。
8.1.5 依赖倒置原则(Dependency Inversion Principle,DIP)
高层模块不应该依赖于低层模块,二者都应该依赖于抽象。抽象不应该依赖于细节,细节应该依赖于抽象。
- 示例:
class Database:
def save(self, data):
pass
class MySQLDatabase(Database):
def save(self, data):
print("Saving data in MySQL database")
class User:
def __init__(self, database: Database):
self.database = database
def save_user(self, data):
self.database.save(data)
# 使用依赖注入
db = MySQLDatabase()
user = User(db)
user.save_user("User data")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
在这个示例中,高层模块(User
类)依赖于抽象(Database
接口),而不是具体实现(MySQLDatabase
类)。
8.2 设计模式
设计模式是解决常见软件设计问题的典型解决方案。以下是一些常见的设计模式:
8.2.1 单例模式(Singleton Pattern)
单例模式确保一个类只有一个实例,并提供全局访问点。
- 示例:
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
# 使用单例模式
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2) # 输出: True
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
8.2.2 工厂模式(Factory Pattern)
工厂模式定义了一个用于创建对象的接口,但由子类决定实例化哪个类。工厂方法让类的实例化推迟到子类。
- 示例:
class Animal:
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("Unknown animal type")
# 使用工厂模式
dog = AnimalFactory.create_animal("dog")
cat = AnimalFactory.create_animal("cat")
print(dog.speak()) # 输出: Woof!
print(cat.speak()) # 输出: Meow!
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
8.2.3 观察者模式(Observer Pattern)
观察者模式定义对象之间的一对多依赖,使得每当一个对象改变状态时,其所有依赖者都会收到通知并自动更新。
- 示例:
class Observer:
def update(self, message):
pass
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
class ConcreteObserver(Observer):
def update(self, message):
print(f"Received message: {message}")
# 使用观察者模式
subject = Subject()
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()
subject.attach(observer1)
subject.attach(observer2)
subject.notify("Observer Pattern in Python")
# 输出:
# Received message: Observer Pattern in Python
# Received message: Observer Pattern in Python
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
这些设计模式和SOLID原则有助于创建更健壮、可维护和可扩展的代码。通过实践和运用这些概念,你可以提升你的软件设计能力。