首页 > 解决方案 > 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}.")

标签: pythonpointersdesign-patternspolymorphismfunction-pointers

解决方案


指针设计模式 (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}.")


推荐阅读