-1

Consider this class containing methods without a self argument:

class C:
    def foo(a,b):
        # function does something
        # It is not an instance method (i.e. no 'self' argument)

    def bar(self):
        # function has to call foo() of the same class
        foo('hello', 'world')

The above code errors when non-instance method foo() is called within bar(). Somehow the name 'foo' is not recognized even though it's a method within the same class body. If it were an instance method, it could be called using self.foo() but here that's not the case.

What's the best way to invoke foo() for the above example?

# 1 Like this?
C.foo('hello', 'world')

# 2 Like this?
self.__class__.foo('hello', 'world')

# Something else?
  • The fact that you named the first parameter of `foo` `a` instead of the traditional `self` doesn't change anything, this is a completely normal method. – Thierry Lathuille Oct 14 '20 at 06:55
  • So you should call it completely normaly, as `self.foo` – Thierry Lathuille Oct 14 '20 at 06:56
  • The things what's you're looking for is a staticmethod I think. You can have a look at python doc https://docs.python.org/3/library/functions.html#staticmethod – Tomasz Sabała Oct 14 '20 at 06:56
  • I'm also confused whether this method is a classmethod or a staticmethod? Classmethods and staticmethods need a decorator and instance methods need a 'self' argument and foo() has none of these 3. So what would you call it? Is it a static method after all? – user3569970 Oct 14 '20 at 07:00
  • @TorbenKlein I find the question still unclear, and I feel that there are lots of misunderstandings about the way different kinds of methods are declared and used. So I would rather recommend spending time on a tutorial about classes and the doc, rather than give an answer. – Thierry Lathuille Oct 14 '20 at 07:01
  • 1
    If it's a static method, you should decorate it as such with `@staticmethod`. Then you can call it any way you want: `C.foo(...)`, `self.foo(...)`. Just `foo(...)` will never work, because it's not a global function. – deceze Oct 14 '20 at 07:01
  • @user3569970 As already said in my first comment, this is a completely ordinary method, the name `self` a a first parameter is a convention, you could use `this` or `oh_dear` or `a` or whatever, this makes no difference. – Thierry Lathuille Oct 14 '20 at 07:02

1 Answers1

-2

You can't define a function with def key words and don't put any indented block right after.

class C:
    def foo(a,b):
        # function does something
        # It is not an instance method (i.e. no 'self' argument)
        return 0

    def bar(self):
        # function has to call foo() of the same class
        foo('hello', 'world')

and then call C.foo('hello','world'). If it is not an instance method you'd better define it as a function outside the class definition though.