在python中调用类方法

ing*_*.am 1 python methods

我想从不同的类调用python中的方法,如下所示:

class foo():
    def bar(name):
        return 'hello %s' % name

def hello(name):
    a = foo().bar(name)
    return a
Run Code Online (Sandbox Code Playgroud)

hello('world')将返回'Hello World'.我知道我在这里做错了什么,有谁知道它是什么?我想这可能是我处理课程的方式,但我还没有理解它.

NPE*_*NPE 6

在Python中,非静态方法明确地将self其作为第一个参数.

foo.bar() 要么是一个静态的方法:

class foo():
    @staticmethod
    def bar(name):
        return 'hello %s' % name
Run Code Online (Sandbox Code Playgroud)

或者必须self作为其第一个参数:

class foo():
    def bar(self, name):
        return 'hello %s' % name
Run Code Online (Sandbox Code Playgroud)

会发生什么,在您的代码中,name被解释为self参数(恰好被称为其他东西).当你调用时foo().bar(name),Python尝试传递两个参数(selfname)foo.bar(),但该方法只需要一个.