Skip to main content
 首页 » 编程设计

python之getattr 错误

2025年05月04日12over140

我要去 Calling a function of a module from a string with the function's name in Python但是每当我在我的程序中调用我的类时,它都会给我这个错误:TypeError: unbound method bar() must be called with foo instance as first argument (got nothing instead)

谁能帮帮我

请您参考如下方法:

这是产生您描述的问题的典型情况。

class Foo(object): 
    def bar(self,x): 
        print(x) 
 
foo=Foo() 

调用 gettatrr(Foo,'bar') 返回未绑定(bind)的方法,Foo.bar。

getattr(Foo,'bar')(1) 

结果

TypeError: unbound method bar() must be called with Foo instance as first argument (got int instance instead)

Foo.bar 方法被称为“未绑定(bind)”,因为在调用时不会将任何实例(例如 foo)作为第一个参数提供。毕竟,如果只提供类 Foo 怎么可能呢?

另一方面,如果您提供类的实例:

getattr(foo,'bar')(1) 

产量

1 

因为 foo.bar 是一个“绑定(bind)”方法——当调用 foo.bar 时,foo 将作为第一个参数提供.

附言。您的错误消息显示,“...调用 foo 实例 ...”。与我上面发布的错误消息相比,您的类似乎被称为小写的 foo。请注意 PEP8 style guide建议总是用大写字母命名类,用小写字母命名实例。这样做将帮助您避免此错误。