# Python编程应用设计原则详解

• 单一职责原则 (SRP)
• 开闭原则 (OCP)
• 里氏替换原则 (LSP)
• 接口隔离原则 (ISP)
• 依赖倒置原则 (DIP)

## 1、单一职责原则 SRP

```import numpy as np

def math_operations(list_):
# Compute Average
print(f"the mean is {np.mean(list_)}")
# Compute Max
print(f"the max is {np.max(list_)}")

math_operations(list_ = [1,2,3,4,5])
# the mean is 3.0
# the max is 5```

```def get_mean(list_):
'''Compute Max'''
print(f"the mean is {np.mean(list_)}")
def get_max(list_):
'''Compute Max'''
print(f"the max is {np.max(list_)}")
def main(list_):
# Compute Average
get_mean(list_)
# Compute Max
get_max(list_)
main([1,2,3,4,5])
# the mean is 3.0
# the max is 5```

• 易读易调试，更容易定位错误。
• 可复用，代码的任何部分都可以在代码的其他部分中重用。
• 可测试，为代码的每个功能创建测试更容易。

## 2、开闭原则 OCP

```import numpy as np
from abc import ABC, abstractmethod
class Operations(ABC):
'''Operations'''
@abstractmethod
def operation():
pass
class Mean(Operations):
'''Compute Max'''
def operation(list_):
print(f"The mean is {np.mean(list_)}")
class Max(Operations):
'''Compute Max'''
def operation(list_):
print(f"The max is {np.max(list_)}")
class Main:
'''Main'''
def get_operations(list_):
# __subclasses__ will found all classes inheriting from Operations
for operation in Operations.__subclasses__():
operation.operation(list_)
if __name__ == "__main__":
Main.get_operations([1,2,3,4,5])
# The mean is 3.0
# The max is 5```

## 3、里氏替换原则 (LSP)

If S is a subtype of T, then objects of type T may be replaced with objects of type S, without breaking the program。

## 4、接口隔离原则 (ISP)

```from abc import ABC, abstractmethod
class Mammals(ABC):
@abstractmethod
def swim(self) -> bool:
pass
@abstractmethod
def walk(self) -> bool:
pass
class Human(Mammals):
def swim(self)-> bool:
print("Humans can swim")
return True
def walk(self)-> bool:
print("Humans can walk")
return True
class Whale(Mammals):
def walk(self) -> bool:
print("Whales can't walk")
return False
def swim(self):
print("Whales can swim")
return True
human = Human()
human.swim()
human.walk()
whale = Whale()
whale.swim()
whale.walk()
```

Humans can swim
Humans can walk
Whales can swim
Whales can't walk

```from abc import ABC, abstractmethod
class Swimer(ABC):
@abstractmethod
def swim(self) -> bool:
pass
class Walker(ABC):
@abstractmethod
def walk(self) -> bool:
pass
class Human(Swimer,Walker):
def swim(self)-> bool:
print("Humans can swim")
return True
def walk(self)-> bool:
print("Humans can walk")
return True
class Whale(Swimer):
def swim(self):
print("Whales can swim")
return True
human = Human()
human.swim()
human.walk()
whale = Whale()
whale.swim()```

## 5、依赖反转原则 (DIP)

• 低层次模块更加通用，适用性更广
• 高层次模块没有依赖低层次模块的具体实现，方便低层次模块的替换