[英]Calling a class method in python
I'm looking to call a method in python from a different class like so: 我正在寻找像这样从另一个类在python中调用方法:
class foo():
def bar(name):
return 'hello %s' % name
def hello(name):
a = foo().bar(name)
return a
Where hello('world') would return 'Hello World'. hello('world')将返回“ Hello World”的地方。 I'm aware I've done something wrong here, does anyone know what it is? 我知道我在这里做错了什么,有人知道这是什么吗? I think it might be the way I'm handling the classes but I haven't got my head around it yet. 我认为这可能是我处理课程的方式,但我还没弄清楚。
In Python, non-static methods explicitly take self
as their first argument. 在Python中,非静态方法显式地将self
作为其第一个参数。
foo.bar()
either needs to be a static method: foo.bar()
要么需要是一个静态方法:
class foo():
@staticmethod
def bar(name):
return 'hello %s' % name
or has to take self
as its first argument: 或必须将self
作为其第一个参数:
class foo():
def bar(self, name):
return 'hello %s' % name
What happens is that in your code, name
gets interpreted as the self
parameter (which just happens to be called something else). 发生的是在您的代码中, name
被解释为self
参数(恰好被称为其他名称)。 When you call foo().bar(name)
, Python tries to pass two arguments ( self
and name
) to foo.bar()
, but the method only takes one. 当您调用foo().bar(name)
,Python尝试将两个参数( self
和name
)传递给foo.bar()
,但是该方法仅采用一个。
You are missing the instance parameter in your method definition: 您在方法定义中缺少实例参数:
class foo():
def bar(self, name):
return 'hello %s' % name
or if you don't intend to use any part of the foo
instance declare the method as a static method. 或者如果您不打算使用foo
实例的任何部分,则将该方法声明为静态方法。 There's a nice explanation between the differences here . 此处的区别之间有很好的解释。
If it's supposed to be a class method, then you should have used the classmethod
decorator and a cls
argument to bar
. 如果应该使用class方法,则应该使用classmethod
装饰器和bar
的cls
参数。 But that makes no sense in this case, so you might have wanted a staticmethod
instead. 但这在这种情况下是没有意义的,因此您可能希望使用staticmethod
。
You missed out the instance parameter, usually named self
: 您错过了通常称为self
的实例参数:
class foo():
def bar(self, name):
return 'hello %s' % name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.