我想像这样从不同的类调用 python 中的方法:
class foo():
def bar(name):
return 'hello %s' % name
def hello(name):
a = foo().bar(name)
return a
hello('world') 会返回 'Hello World'。我知道我在这里做错了什么,有人知道它是什么吗?我认为这可能是我处理类(class)的方式,但我还没有完全理解它。
请您参考如下方法:
在 Python 中,非静态方法显式地将 self 作为它们的第一个参数。
foo.bar() 要么需要是静态方法:
class foo():
@staticmethod
def bar(name):
return 'hello %s' % name
或者必须将 self 作为第一个参数:
class foo():
def bar(self, name):
return 'hello %s' % name
发生的情况是,在您的代码中,name 被解释为 self 参数(恰好被称为其他名称)。当您调用 foo().bar(name) 时,Python 会尝试将两个参数(self 和 name)传递给 foo。 bar(),但该方法只需要一个。
