Arale
Arale

Reputation: 39

How to define a function where it doesn't matter whether you call the class

I am writing a program similar to the short program below:

class Class():
 def __init__(self):
  pass
 def foo():
  pass

Whenever I call foo as Class.foo() everything inside foo works fine.

However, when I call it as Class().foo(), then I get an error: by calling Class I give foo an extra argument, self.
If I added the argument self to foo, then it won't work if I call the function as Class.foo().

How can I avoid this? Any help would be greatly appreciated :)

Upvotes: 0

Views: 98

Answers (1)

wjandrea
wjandrea

Reputation: 32964

It looks like foo should be a staticmethod.

class Class:
    @staticmethod
    def foo():
        pass

print(Class.foo())  # -> None
print(Class().foo())  # -> None

P.S. I can expand on this if needed. The question is a bit vague.

Upvotes: 1

Related Questions