0

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

例如,如果我想在我的新类“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
4

1 回答 1

3

你可以使用混合:

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 类封装了您希望添加到多个类中的某些功能单元,则 Mixin 是有意义的。

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

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)并不明确依赖于它。

于 2013-08-24T12:49:38.023 回答