在Python中扩展类层次结构

时间:2016-04-26 15:01:32

标签: python

我在要扩展的模块中有一个类层次结构。

要扩展的模块看起来像这样。 模块foo:

Private Function NewWorkbook_Open(ByVal clientName As String, ByVal startDateFromSheet As Date) As Workbook

   'Creates/formats new workbook and saves it to the xdrive without any completed
   Dim newWorkBook As Workbook
   Dim activeWorkbookName As String
   Dim formattedDate

   Set newWorkBook = Workbooks.Add

   formattedDate = Replace(Format(startDateFromSheet, "mm/dd/yy"), "/", ".")

   'Saves workbook with new file name with date attached in saveable format
   newWorkBook.SaveAs Filename:=XLS_CONFIRM_FILE_PATH & "-" & GetOfficialClientName(clientName) & " " & formattedDate & ".xls", FileFormat:=xlNormal


   Set NewWorkbook_Open = newWorkBook

End Function

现在我想扩展这些类:

class bar(object): pass
class spam(bar): pass
class eggs(bar): pass

这样做,my_bar中的新函数new_func()将无法在my_spam实例中使用

class my_bar(foo.bar):
    def new_func(): pass
class my_spam(foo.spam): pass
class my_eggs(foo.eggs): pass

实现这一目标的最佳(“最pythonic”)方法是什么?我想到了多重继承,就像这样:

my_spam_instance.new_func()

虽然我之前从未真正使用它,但我不确定这是最好的方法。

2 个答案:

答案 0 :(得分:0)

您甚至不需要从my_bar

继承bar

pythonic 将添加Mixin,它实际上是一个基类,但不是继承的

class NewFuncMixin():
    def new_func(): pass

并将其添加到新类

class my_bar(foo.bar, NewFuncMixin): pass
class my_spam(foo.spam, NewFuncMixin): pass
class my_eggs(foo.eggs, NewFuncMixin): pass

答案 1 :(得分:0)

混合课程怎么样?模式是

class My_mixin( object):
   def new_func(self): pass

class My_spam( My_mixin, foo.spam):  pass
class My_eggs( My_mixin, foo.eggs):  pass

mixins应该从object继承,并在继承列表的左侧,以便mixin类方法获得名称优先级。在mixin中,您可以包装超类的任何方法:

class My_mixin( object):

   def bar_method( self):
      # stuff
      bar_result = super( My_mixin, self).bar_method()
      # more stuff
      return bar_result # or my_result based on bar_result

您当然可以完全覆盖该方法,而不是将其包裹起来。