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.
-
I'm using python 2.7, I think there is some syntax wrong in your code,lostyzd– lostyzd2011年10月07日 16:02:58 +00:00Commented Oct 7, 2011 at 16:02
-
We're on 2.5, not a syntax problem it was the 'self' issue as answered about 4 times below ;)ingh.am– ingh.am2011年10月10日 10:26:16 +00:00Commented Oct 10, 2011 at 10:26
4 Answers 4
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.
1 Comment
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.
Comments
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.
You missed out the instance parameter, usually named self:
class foo():
def bar(self, name):
return 'hello %s' % name