首页 > 解决方案 > Python 嵌套类中的 super()

问题描述

这里发生了什么?

class foo:
    def bogh(self):
        return "foobar"
    class bar:
        def gugh(self):
            return super().bogh()
        
foofoo = foo.bar()
print(foofoo.gugh()) # throws AttributeError: 'super' object has no attribute 'bogh'

看起来它应该工作,对吧?super() 对象不返回包含父类的函数和属性的代理对象吗?但它没有它们。我在 super() 类上运行了一个 dir(),它给了我这个:

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__self_class__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__thisclass__']

没有 bogh() 函数的痕迹。

但是,如果我取消“嵌套”这些功能,我可以让它工作,如下所示:

class foo:
    def bogh(self):
        return "foobar"
    
class bar(foo):
    def gugh(self):
        return super().bogh()
        
foofoo = bar()
print(foofoo.gugh()) # prints "foobar"

如果类是“嵌套的”,为什么它不起作用?有没有办法让它工作?

标签: pythonpython-3.xinheritance

解决方案


它不起作用,因为嵌套类与继承类不同。

如果继承自,那么确实bar会按预期工作。foosuper()

但是嵌套与继承无关,因此类bar无法访问foo.

嵌套的目的仅仅是为了控制可见性。因此,在您的代码示例中,嵌套使得类在类bar之外确实没有任何意义foo,因此不应该成为它自己的顶级类。

再说一遍,总结:嵌套并不意味着继承,因此不会在类之间建立父子关系。

顺便说一句:在您的嵌套示例中,实际上不需要调用super(). 继承的全部意义在于启用自动消息委托。这段代码也同样有效:

class foo:
    def bogh(self):
        return "foobar"
    
class bar(foo):
    def gugh(self):
        return self.bogh()    # No need for super
        
foofoo = bar()
print(foofoo.gugh()) # prints "foobar"

推荐阅读