Python:从类继承/重用特定方法

时间:2013-08-24 12:39:42

标签: python class inheritance methods code-reuse

我想要一个python类,它部分由来自其他类的特定方法组成,这些类在“组合类”中的self上运行。我该怎么做?

E.g。如果我想在我的新类“theClass”中包含classA和classB中的特定方法:

    # Some classes to "inherit" from
    class classA(object):
        def methA1(self, value):
            self.attrib = value*1
        def methA2(self, value):
            self.attrib = value*2
    class classB(object):
        def methB1(self, value):
            self.attrib = value*3
        def methB2(self, value):
            self.attrib = value*4

    # The class I want to build
    class theClass(object):
        # WHAT TO DO HERE?
        # -------------------
        methA1 = classA.methA1
        methB2 = classB.methB2
        # -------------------
        # /WHAT TO DO HERE

        # add additional methods...
        def methC(self, value):
            self.attrib = value*5

    # I want the following behavior
    instance = theClass()
    instance.methB2(5)  # sets instance.attrib to 20
    instance.methA2(5)  # error, does not exist

1 个答案:

答案 0 :(得分:3)

你可以使用mixins:

class MixinA1(object):
    def methA1(self, value):
        self.attrib = value*1
class MixinB2(object):       
    def methB2(self, value):
        self.attrib = value*4
class classA(MixinA1):
    def methA2(self, value):
        self.attrib = value*2
class classB(MixinB2):
    def methB1(self, value):
        self.attrib = value*3

# The class I want to build
class theClass(MixinA1, MixinB2):
    def methC(self, value):
        self.attrib = value*5

如果Mixin类封装了您想要添加到多个类的功能单元,那么Mixins是有意义的。

如果方法不能自然地分解为功能单元, 这是另一种选择:

def methA1(self, value):
    self.attrib = value*1
def methA2(self, value):
    self.attrib = value*2
def methB2(self, value):
    self.attrib = value*4
def methB1(self, value):
    self.attrib = value*3
def methC(self, value):
    self.attrib = value*5

class classA(object):
    methA1 = methA1
    methA2 = methA2    
class classB(object):
    methB1 = methB1
    methB2 = methB2        
class theClass(object):
    methA1 = methA1
    methB2 = methB2
    methC = methC

这与您已经发布的替代方案非常相似,除了它将所有类放在平等的位置之外 - 最初这些方法与任何特定类都没有关联。这可能是优选的,因此theClass不会打破封装"通过从一个类(例如classA)中获取并从中明确依赖的方法中获取方法。