super(MyObject, self).__init__() 在 class MyObject __init__() 函数中做了什么?
What do super(MyObject, self).__init__() do in class MyObject __init__() function?
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'表示父class构造函数,
但我无法理解为什么这两个 class 会调用自己的构造函数 '__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
是在调用基class(当前class继承的class),后面是访问修饰符,访问基class' .__init__()
方法。类似于 self
,但对于基数 class.
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'表示父class构造函数,
但我无法理解为什么这两个 class 会调用自己的构造函数 '__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
是在调用基class(当前class继承的class),后面是访问修饰符,访问基class' .__init__()
方法。类似于 self
,但对于基数 class.