我可以将属性的方法扩展到其父类吗?

时间:2017-02-16 09:55:23

标签: python inheritance

我已经创建了一个新类,其中包含另一个数据结构(在此实例中是一个pandas DataFrame。

除了pandas DataFrame之外,该类还包含其他属性和其他方法。其中一些方法的命名方式与DataFrame中的方法类似,例如to_excel,但在调用DataFrame方法之前还要做一些额外的事情。无论如何,主要成分是这个DataFrame。因此,我希望能够使用DataFrame的所有其他方法,例如getitem,直接在此类的对象上。

class NewDataStructure:
    def __init__(self):
        self.df = pd.DataFrame()
        # have some extra attributes here that the pandas DataFrame doesn't have

    def __getitem__(self, key):
        return self.df.__getitem__(key)

    def to_excel(self, writer):
        # do some extra stuff here that the pandas DataFrame doesn't do but use the pandas method eventually
        self.df.to_excel(writer)

有没有办法将属性的方法扩展到其父类?或者,我是否采取了错误的方式? NewDataStructure应该继承自DataFrame吗?

1 个答案:

答案 0 :(得分:1)

覆盖__getattr__

class NewDataStructure:
    def __init__(self):
        self.df = pd.DataFrame()
        # have some extra attributes here that the pandas DataFrame doesn't have

    def __getitem__(self, key):
        return self.df.__getitem__(key)

    def __getattr__(self, item):
        try:
            return vars(self)[item]
        except KeyError:
            return getattr(self.df, item)

    def to_excel(self, writer):
        # do some extra stuff here that the pandas DataFrame doesn't do but use the pandas method eventually
        self.df.to_excel(writer)

obj = NewDataStructure()
print(obj.ix)
# <pandas.core.indexing._IXIndexer object at 0x01FE7090>
# pandas' ix
print(obj.to_excel)
# <bound method NewDataStructure.to_excel of <__main__.NewDataStructure object at 0x005670F0>>
# NewDataStructure's to_excel

如果我们从to_excel课程中删除NewDataStructure,我们将使用pandas to_excel

class NewDataStructure:
        def __init__(self):
            self.df = pd.DataFrame()
            # have some extra attributes here that the pandas DataFrame doesn't have

        def __getitem__(self, key):
            return self.df.__getitem__(key)

        def __getattr__(self, item):
            try:
                return vars(self)[item]
            except KeyError:
                return getattr(self.df, item)

obj = NewDataStructure()
print(obj.to_excel)
#     <bound method DataFrame.to_excel of Empty DataFrame
#     Columns: []
#     Index: []>

或继承自pd.DataFrame(可能更容易,更好的方式):

class NewDataStructure(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

obj = NewDataStructure()
print(obj.to_excel)
#     <bound method DataFrame.to_excel of Empty DataFrame
#     Columns: []
#     Index: []>
# pandas to_excel

如果我们将to_excel添加到NewDataStructure:

def to_excel(self, *args, **kwargs):
    # do some extra stuff here that the pandas DataFrame doesn't do but use the pandas method eventually
    super().to_excel(*args, **kwargs)
.
.

obj = NewDataStructure()
print(obj.to_excel)
#  <bound method NewDataStructure.to_excel of Empty NewDataStructure
#  Columns: []
#  Index: []>