我遇到了一个使用的代码super()
方法有两种不同的方式,我不明白逻辑上有什么区别。
我现在正在学习pygame
模块,我有一个任务来创建一个类Ball
它继承自Sprite
这是一个来自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()
method)
这些代码块在逻辑上有什么区别?为什么我需要传递到super()
方法参数?这些论点需要是什么?
在 Python-3.x 中,您通常不需要参数super
不再了。那是因为它们被神奇地插入了(参见PEP 3135 -- 新超级 https://www.python.org/dev/peps/pep-3135/).
有参数调用和无参数调用是相同的if:
- 第一个参数是定义该方法的类,该方法使用
super
。在你的情况下是Ball
所以条件满足。
- 和第二个参数
super
is the first该方法的参数。在你的情况下是self
这是该方法的第一个参数,因此也满足条件。
所以在你的情况下有没有不同两个例子之间!
然而,在极少数情况下,您实际上需要致电super
具有不同的参数(具有 1 或 2 个参数/-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
需要参数的调用是很稀少这是一个相当高级的主题,所以我将把它们排除在这个答案之外。
但是,如果您对差异感兴趣,那么一些资源可能会有所帮助:
- 在 Python 3 中调用 super() 的 4 种方法中,使用哪一种? https://stackoverflow.com/q/2771904/5393381
- 如何在 python 中使用带有一个参数的 super() https://stackoverflow.com/q/30190185/5393381
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)