python中super()的使用
Use of super () in python
当我执行以下命令时:
class animal(object):
def desc(self):
print 'animal'
class human():
def desc(self):
print 'human'
class satyr(human, animal):
def desc(self):
print 'satyr'
grover=satyr()
super(satyr, grover).desc()
我懂人性了!
但是人类甚至没有继承 class 对象,我认为 super 只有在 class 对象被继承时才有效。 (新样式class)
现在如果我让 animal 也不继承 class 对象,我会得到一个错误。
这里发生了什么?
之所以这样工作,是因为 classes 或继承的 classes 中只有一个需要从 object
继承,以便您的 class 被创建object
使用的 metaclass。 metaclass 控制此 MRO 行为。
这里是one of the better answers on stack overflow explaining metaclasses。
在 python 3 中,这一切都没有实际意义,因为一切都是 new-style class。此外,确实没有理由 NOT 从 object
继承,所以除非你被迫使用一些不继承自 classes 的旧库object
,你还不如让你所有的 class 继承它。
当我执行以下命令时:
class animal(object):
def desc(self):
print 'animal'
class human():
def desc(self):
print 'human'
class satyr(human, animal):
def desc(self):
print 'satyr'
grover=satyr()
super(satyr, grover).desc()
我懂人性了! 但是人类甚至没有继承 class 对象,我认为 super 只有在 class 对象被继承时才有效。 (新样式class)
现在如果我让 animal 也不继承 class 对象,我会得到一个错误。 这里发生了什么?
之所以这样工作,是因为 classes 或继承的 classes 中只有一个需要从 object
继承,以便您的 class 被创建object
使用的 metaclass。 metaclass 控制此 MRO 行为。
这里是one of the better answers on stack overflow explaining metaclasses。
在 python 3 中,这一切都没有实际意义,因为一切都是 new-style class。此外,确实没有理由 NOT 从 object
继承,所以除非你被迫使用一些不继承自 classes 的旧库object
,你还不如让你所有的 class 继承它。