如果我做这样的事情:
class MyClass(object):
def __init__(self, a=MyClass.f):
self.a = a
@classmethod
def f():
print 'tump drump'
我收到以下错误:
NameError: name 'MyClass' is not defined
显然,我可以这样做:
class MyClass(object):
def __init__(self, a=None):
if a is None:
self.a = MyClass.f
else:
self.a = a
但是有没有更优雅的方法来使用类方法作为类方法的默认参数?
最佳答案
不,没有,因为函数是在类对象之前创建的。这里没有可供引用的类,使用哨兵(如 None
)是执行此操作的正确方法。
请注意,如果您在 中分配给
套件:a
而不是 self.a
,则无需使用 else
套件如果
class MyClass(object):
def __init__(self, a=None):
if a is None:
a = MyClass.f
self.a = a
或者您可以使用条件表达式:
class MyClass(object):
def __init__(self, a=None):
self.a = MyClass.f if a is None else a
甚至:
class MyClass(object):
def __init__(self, a=None):
self.a = a or MyClass.f
如果您需要支持的只是 true 对象(例如,函数对象在 bool 上下文中始终为“true”)。
关于python - 使用类方法作为默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36314308/