【问题标题】:How to use super() to inherit a particular class from multiple father classes?如何使用 super() 从多个父类继承特定类?
【发布时间】:2014-04-25 10:34:29
【问题描述】:

我的代码是这样的,我想用super()来继承papa的特性,怎么做?

class Mama(object):

    def __init__(self):
        self.name = 'Mama'

    def feature(self):
        print "%s have big eyes" % self.name

class Papa(object):

    def __init__(self):
        self.name = 'Papa'

    def feature(self):
        print "%s have fierce beards" % self.name

class Offspring(Mama,Papa):
    def __init__(self, name):
        self.name = name

    def feature(self):
        super(Offspring, self).feature()

offspring = Offspring('Tommy')

offspring.feature()

# This will result "Tommy have big eyes"

【问题讨论】:

    标签: python inheritance multiple-inheritance super


    【解决方案1】:

    你可以通过继承Papa来改变MRO(方法解析顺序)first

    class Offspring(Papa, Mama):
    

    另一种方法是跳过 MRO 并显式调用 Papa 上的(未绑定)方法:

    class Offspring(Mama, Papa):
        def __init__(self, name):
            self.name = name
    
        def feature(self):
            Papa.feature(self)
    

    【讨论】:

    • 又是你比我快+1
    • 我认为第二种方式可能是适合我的情况的解决方案。
    【解决方案2】:

    您的 heirachy 中的所有类都需要使用 super 才能通过 所有 方法。最终,您会遇到一个问题,即下一个超类是object,它没有feature,因此您还需要检测这种情况并忽略它——即,您需要这样做:

    class Mama(object):
    
        def __init__(self):
            self.name = 'Mama'
    
        def feature(self):
            try:
                super(Mama, self).feature()
            except AttributeError:
                # only superclass is object
                pass
            print "%s have big eyes" % self.name
    
    class Papa(object):
    
        def __init__(self):
            self.name = 'Papa'
    
        def feature(self):
            try:
                super(Papa, self).feature()
            except AttributeError:
                # only superclass is object
                pass
            print "%s have fierce beards" % self.name
    
    class Offspring(Mama,Papa):
        def __init__(self, name):
            self.name = name
    
        def feature(self):
            super(Offspring, self).feature()
    

    除了捕获 AttributeError 之外,您还可以创建一个仅存在的进一步类,以提供feature(无需调用super)以供其他类继承。然后 Mama 和 Papa 都继承该类并覆盖 feature,如下所示:

     class Grandma(object):
         def feature(self):
             pass
    
     class Mama(Grandma):
         def feature(self):
            super(Mama, self).feature()
            print "%s have big eyes" % self.name
    

    可能想考虑将feature 设为abstractmethod,以强调它的存在只是为了继承。

    在任何一种情况下,您都会继续调用下一个方法,直到到达链的末尾。如果MamaPapa 都没有调用super,你总是会在一个调用后停止。

    【讨论】:

    • 谢谢。我只想在这里知道如何获得所需父类的方法。我今天下午研究了一点。如果有多级父类有相同的方法。只是 super(target_father_class, self).method() 会调用那个father_class的父方法。
    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多