class MyObject1(object):
def __init__(self):
super(MyObject1, self).__init__()
pass
class MyObject2(object):
def __init__(self, arg):
super(MyObject2, self).__init__()
pass
我读过这样的python27代码,
我知道“super”意味着父类构造函数,
但我不明白为什么这两个类称自己为“构造函数”__init__
',
好像没有什么实际作用。
最佳答案
这些是 Python 中一些非常基本的 OO 方法。阅读 here .
super
和 self
类似:
super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.
(来自此answer)
以下是 super
的实际应用示例:
class Animal(object):
def __init__(self, speed, is_mammal):
self.speed = speed
self.is_mammal = is_mammal
class Cat(Animal):
def __init__(self, is_hungry):
super().__init__(10, True)
self.is_hungry = is_hungry
barry = Cat(True)
print(f"speed: {barry.speed}")
print(f"is a mammal: {barry.is_mammal}")
print(f"feed the cat?: {barry.is_hungry}")
可以看到super
正在调用基类(当前类继承的类),后面跟着一个访问修饰符,访问基类的.__init__()
方法。它类似于 self
,但用于基类。
关于python - super(MyObject, self).__init__() 在类 MyObject __init__() 函数中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38586279/