python - 尝试调用类方法的代码中的各种错误

标签 python class-method

我有这个代码:

class SomeClass:
    @classmethod
    def func1(cls,arg1):
        #---Do Something---
    @classmethod
    def func2(cls,arg1):
        #---Do Something---

    # A 'function map' that has function name as its keys and the above function
    # objects as values
    func_map={'func1':func1,'func2':func2}

    @classmethod
    def func3(cls,arg1):
        # following is a dict(created by reading a config file) that
        # contains func names as keys and boolean as values that tells
        # the program whether or not to run that function
        global funcList
        for func in funcList:
            if funcList[func]==True:
                cls.func_map[func](arg1)        #TROUBLING PART!!!

    if _name__='main'
        SomeClass.func3('Argumentus-Primus')

当我运行它时,我不断收到错误:

Exception TypeError: "'classmethod' object is not callable"

我无法弄清楚这有什么问题,希望您能提供帮助。

最佳答案

在定义类之前,您不能创建对类方法的引用。您必须将其移出类定义。然而,使用全局函数映射来决定运行什么真的很尴尬。如果您描述了您要如何处理此问题,我们可能会建议一个更好的解决方案。

class SomeClass(object):
    @classmethod
    def func1(cls, arg1):
        print("Called func1({})".format(arg1))

    @classmethod
    def func2(cls, arg1):
        print("Call func2({})".format(arg1))

    @classmethod
    def func3(cls, arg1):
        for fnName,do in funcList.iteritems():
            if do:
                try:
                    cls.func_map[fnName](arg1)
                except KeyError:
                    print("Don't know function '{}'".format(fnName))

# can't create function map until class has been created
SomeClass.func_map = {
    'func1': SomeClass.func1,
    'func2': SomeClass.func2
}

if __name__=='__main__':
    funcList = {'func1':True, 'func2':False}
    SomeClass.func3('Argumentus-Primus')

关于python - 尝试调用类方法的代码中的各种错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11058686/

相关文章:

不能从 class.__dict__ 调用 python 类方法

python - 从字典创建数据框,其中值是可变长度列表

python - 如何索引 Pandas 数据框中的时间段?

python - Pandas Dataframe 对 ms 值重新采样

ruby - Swift 实例 vs 类方法加上类继承

objective-c - 在类方法中使用 self

ruby - 如何理解class_eval()和instance_eval()的区别?

python - 如何在 OpenGL 中将矩阵渲染为立方体?

python - 将列表元素转换为另一个列表的列表列表

ruby - 为什么我的 Ruby 脚本会随着时间的推移变慢?