问题描述
super 有 2 个参数,
super has 2 args,
super(type, obj_of_type-or-subclass_of_type)
我了解如何以及为什么使用 super 并且第二个参数是 obj_of_type.但我不明白第二个参数是子类的问题.
I understand how and why to use super with the 2nd arg being obj_of_type.But I don't understand the matter for the 2nd arg being subclass.
谁能说明原因和方法?
推荐答案
如果你想调用一个实例方法,你可以传递一个对象.如果要调用类方法,则传递一个类.
You pass an object if you want to invoke an instance method. You pass a class if you want to invoke a class method.
将super()
用于类方法的经典示例是使用工厂方法,您希望在其中调用所有超类工厂方法.
The classic example for using super()
for class methods is with factory methods, where you want all the superclass factory methods to be called.
class Base(object):
@classmethod
def make(cls, *args, **kwargs):
print("Base.make(%s, %s) start" % (args, kwargs))
print("Base.make end")
class Foo(Base):
@classmethod
def make(cls, *args, **kwargs):
print("Foo.make(%s, %s) start" % (args, kwargs))
super(Foo, cls).make(*args, **kwargs)
print("Foo.make end")
class Bar(Base):
@classmethod
def make(cls, *args, **kwargs):
print("Bar.make(%s, %s) start" % (args, kwargs))
super(Bar, cls).make(*args, **kwargs)
print("Bar.make end")
class FooBar(Foo,Bar):
@classmethod
def make(cls, *args, **kwargs):
print("FooBar.make(%s, %s) start" % (args, kwargs))
super(FooBar, cls).make(*args, **kwargs)
print("FooBar.make end")
fb = FooBar.make(1, 2, c=3)
"在 Python 中调用超类的类方法" 有一个现实世界的例子.
"Invoking a superclass's class methods in Python" has a real-world example.
这篇关于为什么以及如何使用 Python 的 super(type1, type2)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!