Calling a class method in python
I'm looking to call a method in python from a different class like so:
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'. 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.
foo.bar()
either needs to be a static method:
class foo():
@staticmethod
def bar(name):
return 'hello %s' % name
or has to take self
as its first argument:
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). When you call foo().bar(name)
, Python tries to pass two arguments ( self
and name
) to foo.bar()
, but the method only takes one.
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. 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
. But that makes no sense in this case, so you might have wanted a staticmethod
instead.
下一篇: 在python中调用一个类方法