【问题标题】:Call a parent class method from a child class in Python 2在 Python 2 中从子类调用父类方法
【发布时间】:2014-07-07 22:55:25
【问题描述】:

我想在 Python 2 中使用 super() 调用父类方法。

在 Python 3 中,我会这样编码:

    class base:
        @classmethod    
        def func(cls):
            print("in base: " + cls.__name__)

    class child(base):
        @classmethod    
        def func(cls):
            super().func()
            print("in child: " + cls.__name__)

    child.func()

这个输出:

    in base: child
    in child: child

但是,我不知道如何在 Python 2 中做到这一点。当然,我可以使用 base.func(),但我不喜欢另外指定父类名称,主要是我得到了不需要的结果:

    in base: base
    in child: child

使用cls (cls is child) 作为super() 函数调用中的第一个参数,我收到此错误:

    TypeError: must be type, not classobj

知道如何使用super() 或我不必指定父类名称的类似函数吗?

【问题讨论】:

  • 提示:复制粘贴你的问题到谷歌搜索

标签: python inheritance parent-child superclass super


【解决方案1】:

你的父对象需要继承自 python 2 中的对象。所以:

class base(object): 
    def func(self):
        print("in base")

class child(base):
    def func(self):
        super(child, self).func()
        print("in child")

c = child()
c.func()

【讨论】:

    【解决方案2】:

    进一步提出其他答案,您可以为它做类方法

    class base(object):
            @classmethod    
            def func(cls):
                print("in base: " + cls.__name__)
    
    class child(base):
            @classmethod    
            def func(cls):
                super(cls, cls).func() 
                print("in child: " + cls.__name__)
    
    child.func()
    

    【讨论】:

    • 谢谢,这就是我想要的:)
    • 应该是super(child, cls)。否则child 的子类以无限递归调用func 结束。
    【解决方案3】:

    我试图做一些类似的事情,我试图基本上“走上”继承链,直到找到某个基类,然后用类名在那里做一些事情。我遇到的问题是,所有这些答案都假设您知道您想要获得超级的类的名称。我尝试了“超级(cls,cls)”方法,但遇到了上述“无限递归”问题。这是我降落的地方

    @classmethod
    def parent_name(cls):
        if BaseDocument in cls.__bases__:
            # This will return the name of the first parent that subclasses BaseDocument
            return cls.__name__
        else:
            for klass in cls.__bases__:
                try:
                    parent_name = klass.parent_name()
                    if parent_name is not None:
                        return parent_name
                except AttributeError:
                    pass
    
            return None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 2012-02-22
      • 2014-09-23
      • 1970-01-01
      • 2013-07-16
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多