繁体   English   中英

Python 的嵌套类中的 super()

[英]super() in nested classes in Python

这里发生了什么?

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() object 不会返回包含父类的函数和属性的代理 object 吗? 但它没有它们。 我在 super() class 上运行了一个 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() function 没有踪迹。

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

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

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

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

如果bar会从foo继承,那么super()确实会按预期工作。

但是嵌套与 inheritance 无关,因此 class bar无法访问foo的任何方法。

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

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

顺便说一句:在您的嵌套示例中,实际上不需要调用super() inheritance 的重点是启用自动消息委托。 这段代码也同样有效:

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM