所以,我有一个类,其中一个类变量被设置为 __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 实例作为第一个参数调用(改为获取列表)
发生这种情况是因为 MyBar
在 Foo
和 MyFoo
中有相同的名称,还是这里有其他问题?
作为引用,两个 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/