2017-02-16 108 views
0

我已經創建了所有包含另一種數據結構(在這種情況下一個熊貓數據幀的新類。我可以將屬性的方法擴展到其父類嗎?

這個類就會有其他的屬性和它的其他方法,除了大熊貓數據幀。有些方法的命名方式與DataFrame中的方法類似,例如,to_excel,但在調用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

要麼覆蓋__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 

如果我們從NewDataStructure類中刪除to_excel,我們將使用大熊貓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: []> 
相關問題