python - 使用类方法作为默认参数

标签 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' 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/

相关文章:

python-2.7 - 由于 Windows 程序文件权限,conda 更新 conda 无法正常工作

python - django-appengine 服务器未启动

python - subprocess.Popen 在 Windows 和 Mac OS 之间有何不同?

python - 不带 Pandas 的 CSV 分组

python - 为python包创建模块

python-2.7 - Scikit-learn RandomForestClassifier()特征选择,只选择训练集?

python - 以最佳方式迭代 pandas 中的数百万行

java简单的对象数组

java - 是先创建一个对象然后执行它的构造函数吗?

javascript - 使用原型(prototype)的最佳方式 [OOP]