带参数和不带参数的 super() 有什么区别?
What is the difference between super() with arguments and without arguments?
我遇到了以两种不同方式使用 super()
方法的代码,我不明白逻辑上有什么不同。
我现在正在学习 pygame
模块,我的任务是创建 Ball
的 class,它继承自 Sprite
class 来自 pygame
模块(如果我没记错的话)。
我遇到了这段代码:
import pygame
class Ball(pygame.sprite.Sprite):
def __init__(self, x, y):
super(Ball, self).__init__()
我无法理解与以下内容的区别:
import pygame
class Ball(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
(super()
方法的参数)
这些代码块在逻辑上有什么区别?为什么我需要传递给 super()
方法参数?那些参数必须是什么?
在 Python-3.x 中,您通常不再需要 super
的参数。那是因为它们是神奇地插入的(参见 PEP 3135 -- New Super)。
双参数调用和无参数调用是相同的if:
- 第一个参数是 class,其中定义了使用
super
的方法。在你的情况下它是 Ball
所以条件被满足。
-
super
的第二个参数是方法的 第一个 参数。在您的情况下,self
是该方法的第一个参数,因此也满足该条件。
因此在您的情况下,两个示例之间没有区别!
然而,在极少数情况下,您实际上需要使用不同的参数调用 super
(使用 1 或 2 argument/-s)。 super 的文档是一个很好的起点:
>>> help(super)
Help on class super in module builtins:
class super(object)
| super() -> same as super(__class__, <first argument>)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
| Typical use to call a cooperative superclass method:
但我认为您的问题主要是关于示例中的差异(没有差异),并且这些 super
需要参数的调用 非常罕见 并且相当高级的主题,所以我将把它们排除在这个答案之外。
但是,如果您对差异感兴趣,有些资源可能会有所帮助:
- Which of the 4 ways to call super() in Python 3 to use?
- How can I use super() with one argument in python
我遇到了以两种不同方式使用 super()
方法的代码,我不明白逻辑上有什么不同。
我现在正在学习 pygame
模块,我的任务是创建 Ball
的 class,它继承自 Sprite
class 来自 pygame
模块(如果我没记错的话)。
我遇到了这段代码:
import pygame
class Ball(pygame.sprite.Sprite):
def __init__(self, x, y):
super(Ball, self).__init__()
我无法理解与以下内容的区别:
import pygame
class Ball(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
(super()
方法的参数)
这些代码块在逻辑上有什么区别?为什么我需要传递给 super()
方法参数?那些参数必须是什么?
在 Python-3.x 中,您通常不再需要 super
的参数。那是因为它们是神奇地插入的(参见 PEP 3135 -- New Super)。
双参数调用和无参数调用是相同的if:
- 第一个参数是 class,其中定义了使用
super
的方法。在你的情况下它是Ball
所以条件被满足。 -
super
的第二个参数是方法的 第一个 参数。在您的情况下,self
是该方法的第一个参数,因此也满足该条件。
因此在您的情况下,两个示例之间没有区别!
然而,在极少数情况下,您实际上需要使用不同的参数调用 super
(使用 1 或 2 argument/-s)。 super 的文档是一个很好的起点:
>>> help(super)
Help on class super in module builtins:
class super(object)
| super() -> same as super(__class__, <first argument>)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
| Typical use to call a cooperative superclass method:
但我认为您的问题主要是关于示例中的差异(没有差异),并且这些 super
需要参数的调用 非常罕见 并且相当高级的主题,所以我将把它们排除在这个答案之外。
但是,如果您对差异感兴趣,有些资源可能会有所帮助:
- Which of the 4 ways to call super() in Python 3 to use?
- How can I use super() with one argument in python