Python中的“TypeError:无法示例化抽象类”

kuhbmx9i  于 2022-11-26  发布在  Python
关注(0)|答案(2)|浏览(165)

我有一个模块fi,其中定义了以下类:

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()

然后我有另一个类Bond(fi.Asset),其中包含以下方法:

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)

当我调用to_cash_flows时,得到错误TypeError: Can't instantiate abstract class CashFlows with abstract methods get_price。我看到了this answer,但无法将其与我当前的问题联系起来。
谢谢您

9cbw7uwe

9cbw7uwe1#

您的CashFlows类需要定义get_price的实现;它是一个抽象方法,具体子类必须实现它。

fykwrbwg

fykwrbwg2#

需要重写**CashFlows中的get_price()抽象方法**,如下所示:

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"

相关问题