python - 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"
如果类是“嵌套的”,为什么它不起作用?有没有办法让它工作?
解决方案
它不起作用,因为嵌套类与继承类不同。
如果继承自,那么确实bar
会按预期工作。foo
super()
但是嵌套与继承无关,因此类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"
推荐阅读
- sql - 最长公共子串、BigQuery、SQL
- scala - 如何读取 csv 文件并将值分配给 spark scala 中的变量
- wordpress - Woocommerce:当前类别的产品类别小部件
- javascript - 使用 document.cookie 在不同的子域上创建 cookie
- javascript - 将对象存储在数组中
- c++ - 如何使用 CMake 整理我的相关引用?
- node.js - 如何在 Postgresql 的事务中执行 If-Else 条件
- c++ - 默认构造函数 (C++) 中的用户输入。这可以做到吗?
- flutter - Flutter:滑动时在页面浏览中添加新页面
- c# - 如何使用 MVVM 将来自 Restful 服务的图像显示到 Xamarin.Forms 视图