为什么在使用 super() 时必须指定自己的类,有没有办法解决它?
当使用Python的super()
进行方法链接时,你必须显式指定你自己的类,例如:
class MyDecorator(Decorator):
def decorate(self):
super(MyDecorator, self).decorate()
我必须指定我的类的名称MyDecorator
作为参数到super()
。 这不是干的。 当我现在重命名我的班级时,我将不得不重命名两次。 为什么要这样实现呢? 有没有办法避免将类名写两次(或更多次)?
When using Python's super()
to do method chaining, you have to explicitly specify your own class, for example:
class MyDecorator(Decorator):
def decorate(self):
super(MyDecorator, self).decorate()
I have to specify the name of my class MyDecorator
as an argument to super()
. This is not DRY. When I rename my class now I will have to rename it twice. Why is this implemented this way? And is there a way to weasel out of having to write the name of the class twice(or more)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在Python 3.0中,您可以使用
super()
,它相当于super(ThisClass, self)
。文档此处。 文档中的代码示例:
In Python 3.0, you can use
super()
which is equivalent tosuper(ThisClass, self)
.Documentation here. Code sample from the documentation:
BDFL 对此表示同意。 在 Python 3.0 中,添加了对不带参数的
super()
的支持:另请参阅 Python 2.6 的 Pep 367 - New Super。
The BDFL agrees. In Python 3.0, support for
super()
with no arguments was added:Also see Pep 367 - New Super for Python 2.6.
这个答案是错误的,尝试一下:
在Python 2中有一种使用装饰器的方法:
This answer is wrong, try:
In Python 2 there is a way using decorator:
您还可以避免在旧版本的 python 中编写具体的类名,方法是使用
you can also avoid writing a concrete class name in older versions of python by using