使用classmethod作为默认参数

时间:2016-03-30 16:15:03

标签: python python-2.7 oop class-method

如果我这样做:

class MyClass(object):
    def __init__(self, a=MyClass.f):
         self.a = a

    @classmethod
    def f():
         print 'tump drump'

我收到以下错误:

  

NameError:name' MyClass'未定义

显然,我可以这样做:

class MyClass(object):
    def __init__(self, a=None):
         if a is None:
              self.a = MyClass.f
         else:
              self.a = a

但使用classmethod作为类方法的默认参数是否有更优雅的方法?

1 个答案:

答案 0 :(得分:3)

不,没有,因为函数是在类对象之前创建的。这里没有要引用的类,使用标记(如None)是正确的方法。

请注意,如果您在else套件中指定a而不是self.a,则无需使用if套件:

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

如果你需要支持的只是truthy对象(例如,函数对象在布尔上下文中总是'true')。