【问题标题】:Iterate over certain methods of child classes within a given parent class迭代给定父类中子类的某些方法
【发布时间】:2018-03-16 16:04:31
【问题描述】:

我构建了两个名为 zero_coupon_bond 和 coupon_bond 的类,它们都有一个名为 Create_random_asset 的方法,它为两种产品生成随机数据属性(notionals、start_date、end_date、Riskdate 等)并在数据框中返回该数据(带有 n行)。现在我想写一个名为 product_collection,它继承了两个类并迭代了两个子类(会有更多的产品,这就是为什么我想用迭代来做),并使用方法 create_random_asset 为每个子类返回这些数据帧。在代码中:

class zero_coupon_bond():

    def __init__(self):
        ..........


    def create_random_asset(self,n):
        .....
        return pd.DataFrame(OrderedDict(self.columns))

class coupon_bond():

    def __init__(self):
        ..........

    def create_random_asset(self,n):
        .....
        return pd.DataFrame(OrderedDict(self.columns))

然后我正在寻找类似的东西:

class product_collection(zero_coupon_bond,coupon_bond):

    def __init__(self,n,k):
        self.n=n
        self.k=k
        self.df="empty dateframe"


    def random_data(self,n,amount_products):

               for product in childclass:
                    df.append(childclass.create_random_asset(n))

任何人知道我该如何正确实现它?提前致谢。

【问题讨论】:

  • 听起来继承在这里不是一个好的选择。你想要两个类的实例
  • 您知道如何有效地收集两种产品的数据并将它们加入一个数据框吗?

标签: python class parent-child


【解决方案1】:

根据您在问题中提供的内容,您的 product_collection 类不应继承(也不是其祖先)您的优惠券类。相反,它应该尽可能地与coupon_bond 类解耦。也就是说,它应该能够识别和迭代任何实现方法create_random_asset的对象。

product_collection 类可以管理其元素类型为 coupon_bond 的内部集合(可能是 list)。

那么你的random_data 方法可以这样实现:

class product_collection():
    def __init__(self):
        self.products = []

    # ...

    def random_data(self):
        df = # empty dataframe
        for p in self.products:
            df.append(p.create_random_asset())
        return df

要将不同的产品添加到您的产品集合中,您可以在 product_collection 中实现一个 add_product 方法,该方法只是将一个 coupon_bond 实例附加到产品的内部列表中。

def add_prodct(self, product):
    assert product
    self.products.append(product)

【讨论】:

  • 在这种情况下,我收到一个错误,即“产品集合”没有创建数据框所需的属性,例如在创建随机资产中,一行是位置的 ID,所以我得到:create_random_asset ID=self.ID(n) AttributeError: 'product_collection' object has no attribute 'ID'
  • 我现在使用了你的方法,但也继承了子债券类,因为它们是另一个子类“固定收益产品”的父类,我也需要一些方法用于数据框现在它可以工作了..谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 2011-07-28
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多