1

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.

2
  • I'm using python 2.7, I think there is some syntax wrong in your code, Commented 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 ;) Commented Oct 10, 2011 at 10:26

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I've only done minimal python in the past! Thanks though.
3

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

3

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.

1 Comment

And a classmethod has the class (usually called cls) as first parameter, so you'd have to add that too.
3

You missed out the instance parameter, usually named self:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.