-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?
7
  • 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. Commented Oct 14, 2020 at 6:55
  • So you should call it completely normaly, as self.foo Commented Oct 14, 2020 at 6:56
  • The things what's you're looking for is a staticmethod I think. You can have a look at python doc docs.python.org/3/library/functions.html#staticmethod Commented Oct 14, 2020 at 6: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? Commented Oct 14, 2020 at 7:00
  • 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. Commented Oct 14, 2020 at 7:01

1 Answer 1

-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.

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

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.