samedi 4 juillet 2020

What is the Pointer Design Pattern (PDP) for function pointers in Python?

How can I practice polymorphism in Python?

Let's assume a very simplified version of option pricing algorithm, which only needs three inputs (option_type, spot_price and strike_price) to determine the intrinsic value of our option. Please have a look at the example code below.

Although, I have used the inheritance to make my code more manageable, the implementation of method "calculate_option_price" is not stable. That is due to the fact that a new elif should be added for each new option_type in the future. In other words, by adding more elif for each new option_type in the future, the implementation size may grow undesirably and becomes more prone to mistake during future developments. How can I solve that issue in Python by replicating the behaviour of function pointers in C++ & C#?

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}.")

Aucun commentaire:

Enregistrer un commentaire