python - Python 中函数指针的指针设计模式 (PDP) 是什么?
问题描述
如何在 Python 中练习多态性?
让我们假设一个非常简化版本的期权定价算法,它只需要三个输入(option_type、spot_price 和strike_price)来确定我们期权的内在价值。请看下面的示例代码。
虽然,我使用继承使我的代码更易于管理,但方法“calculate_option_price”的实现并不稳定。这是因为将来应该为每个新的 option_type 添加一个新的 elif。换句话说,通过在未来为每个新的 option_type 添加更多的 elif,实现规模可能会不希望地增长,并且在未来的开发中变得更容易出错。如何通过在 C++ 和 C# 中复制函数指针的行为来解决 Python 中的该问题?
from abc import ABC, abstractmethod
import attr
@attr.s(auto_attribs=True, frozen=True)
class Option(ABC):
strike_price:float
@abstractmethod
def price(self, spot_price: float):
raise NotImplementedError("This method must be implemented in the subclasses.")
class Call(Option):
def price(self,spot_price: float) -> float:
return spot_price - self.strike_price
class Put(Option):
def price(self,spot_price: float) -> float:
return self.strike_price - spot_price
def calculate_option_price(option_type:str, spot_price:float, strike_price:float) -> float:
if option_type == "CALL":
return Call(strike_price=strike_price).price(spot_price=spot_price)
elif option_type == "PUT":
return Put(strike_price=strike_price).price(spot_price=spot_price)
option_price = calculate_option_price(option_type="CALL", spot_price=120, strike_price=80)
print(f"option price is {option_price}.")
解决方案
指针设计模式 (PDP) 使您能够在 Python 中练习多态性,并部分复制函数指针的行为,类似于它们在 C++ 和 C# 中的工作方式。与 C++ 相比,如果在 Python 中使用 PDP,则无需担心指针的经典缺点,例如内存泄漏。
指针设计模式 (PDP) 使用枚举对象将所有潜在的选项类型映射到它自己的对应对象。更重要的是,这稳定了“calculate_option_price”方法的实现,以供将来开发,因为如果将来添加新的选项类型,则不需要对其进行修改。请看下面的例子:
from enum import Enum, unique
from abc import ABC, abstractmethod
import attr
@attr.s(auto_attribs=True, frozen=True)
class Option(ABC):
strike_price:float
@abstractmethod
def price(self, spot_price: float):
raise NotImplementedError("This method must be overrode in the subclasses.")
class Call(Option):
def price(self,spot_price: float) -> float:
return spot_price - self.strike_price
class Put(Option):
def price(self,spot_price: float) -> float:
return self.strike_price - spot_price
@unique
class OptionType(Enum):
PUT=Put
CALL=Call
def calculate_option_price(option_type:str, spot_price:float, strike_price:float) -> float:
pointer = OptionType[option_type].value
return pointer(strike_price=strike_price).price(spot_price=spot_price)
option_price = calculate_option_price(option_type="CALL", spot_price=120, strike_price=80)
print(f"option price is {option_price}.")
推荐阅读
- javascript - 编辑表单中 onChange 的 JSX 字典问题
- crystal-reports - 将两个参数从主报表传递到水晶报表中相同数据集的子报表
- neural-network - Word2vec:共享投影层是什么意思?
- node.js - nodejs上的'EVP_DecryptFinal_ex:错误解密'错误
- reactjs - 如何通过 NPM 将我的 React 组件用作共享组件库?
- python - 一个关于删除元素的程序被接受,但另一个不被接受
- r - 分配 n 个 NumericMatrix 的 Rcpp 列表
- uiimage - iOS:合并两张图片,合并重叠的内容
- android - 无法将获取的值从 firebase 数据库保存到列表
- javascript - 如何根据值验证内容可编辑的段落文本长度