"TypeError: Can't instantiate abstract class" in Python
Asked Answered
R

2

10

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

Reverie answered 12/8, 2015 at 19:12 Comment(0)
G
18

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

Griffin answered 12/8, 2015 at 19:16 Comment(0)
T
0

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"
Tholos answered 20/11, 2022 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.