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.

neatnick
  • 1,489
  • 1
  • 18
  • 29
ingh.am
  • 25,981
  • 43
  • 130
  • 177

4 Answers4

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
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.

Community
  • 1
  • 1
GWW
  • 43,129
  • 11
  • 115
  • 108
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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 3
    And a `classmethod` has the class (usually called `cls`) as first parameter, so you'd have to add that too. –  Oct 07 '11 at 16:02
3

You missed out the instance parameter, usually named self:

class foo():
    def bar(self, name):
        return 'hello %s' % name
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490