2017-02-16 37 views
0

私はその中に別のデータ構造(この例ではパンダのデータフレームを含む新しいクラスを作成しました。属性のメソッドを親クラスに拡張できますか?

このクラスは、パンダのデータフレームに加えて、他の属性とその中の他の方法を持っているでしょう。これらのいくつかをメソッドは、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

どちらか__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_excelNewDataStructureからクラスを削除した場合、私たちはパンダ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 

NewDataStructureにto_excelを追加した場合:

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: []> 
関連する問題