python - Python 类和工厂方法中未绑定(bind)方法的类型错误

标签 python class

所以,我有一个类,其中一个类变量被设置为 __init__ 方法中类工厂的输出,如下所示:

def MyFooFactory():
    def __init__(self, *args):
        # Do __init__ stuff

    def MyBar(myFoo_obj):
        print "MyBar"

    newclass = type("MyFoo", tuple(object), {"__init__": __init__, "MyBar": MyBar} )
    return newclass

class Foo:
    Bar = 0
    def __init__(self):
        if (type(Foo.Bar) is int):
            Bar = MyFooFactory()

    def MyBar(a_list):
        for l in a_list:
            Bar.MyBar(l)

但是,当我尝试这个的时候

myBar_list = [Foo.Bar() for _ in range(x)]
Foo.MyBar(myBar_list)

TypeError:未绑定(bind)方法 MyBar() 必须使用 Foo 实例作为第一个参数调用(改为获取列表)

发生这种情况是因为 MyBarFooMyFoo 中有相同的名称,还是这里有其他问题?

作为引用,两个 MyBar 方法都应该是未绑定(bind)的。

谢谢,

最佳答案

Python 中的实例方法 必须self 作为第一个参数(其中 self 实际上只是一个形式参数名称,就像其他任何参数一样 - 它得到由于是第一个而绑定(bind)到实例),所以你有

def MyBar(self, a_list):
    ...

另一方面,如果您确实想要一个静态 方法,则必须use the @staticmethod decorator :

@staticmethod
def MyBar(a_list):
    ...

另请参阅此答案:What is the difference between @staticmethod and @classmethod in Python?

关于python - Python 类和工厂方法中未绑定(bind)方法的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32367825/

相关文章:

python - 多项式NB错误: "Unknown Label Type"

python - Twilio - 如何处理 <gather> 上没有输入的情况

python - 在 Python Pandas 中使用多个 'Value' 列拆分 DataFrame

visual-studio - "type ' int ' unexpected"在构造函数中,找不到为什么?

javascript - JavaScript 对象中的私有(private)变量定义

Python 尝试 block 大小

python - 如何映射到字典

java - 为什么一个final类不能被继承,一个final方法却可以被继承?

javascript - 从类中设置的点击处理程序中使用 setTimeout 调用 javascript 类函数

ios - 数组中的数组(二维数组?)