开发者

Calling a class method in python

开发者 https://www.devze.com 2023-04-11 06:14 出处:网络
I\'m looking to call a method in python from a different class like so: 开发者_StackOverflow class foo():

I'm looking to call a method in python from a different class like so:

开发者_StackOverflow
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.


You missed out the instance parameter, usually named self:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号