"TypeError: Can't instantiate abstract class" in Python

Question:

I have a module fi with the following classes defined:

class Asset(metaclass=abc.ABCMeta):
    pass

    @abc.abstractmethod
    def get_price(self, dt : datetime.date, **kwargs):
    ''' Nothing here yet
    '''

class CashFlows(Asset):

   def __init__(self, amounts : pandas.Series, probabilities : pandas.Series = None):
   amounts = Asset.to_cash_flows()

I then have another class Bond(fi.Asset) with this method within it:

def to_cash_flows(self, notional : float = 100.0) -> fi.asset.CashFlows:
    series = pandas.Series(list_of_data, indices_of_data)
    return fi.CashFlows(series)

I get the error TypeError: Can't instantiate abstract class CashFlows with abstract methods get_price when I call to_cash_flows. I’ve seen this answer, but am unable to relate it with my current issue.

Thank You

Asked By: user131983

||

Answers:

Your CashFlows class needs to define an implementation of get_price; it’s an abstract method and concrete subclasses must implement it.

Answered By: Wooble

You need to override get_price() abstract method in CashFlows class as shown below:

class Asset(metaclass=abc.ABCMeta):
    
    @abc.abstractmethod
    def get_price(self, dt : datetime.date, **kwargs):
        pass

class CashFlows(Asset):

    def __init__(
        self, 
        amounts : pandas.Series, 
        probabilities : pandas.Series = None
    ):
        amounts = Asset.to_cash_flows()
    
    # You need to override
    def get_price(self, dt : datetime.date, **kwargs):
        return "Hello"
Answered By: Kai – Kazuya Ito