-1

Suppose I have the following:

class myClass:
  def foo(self):
    # do something

How can I call myClass from inside the class without declaring an new myClass Object? i.e. I'd like something like

class myClass:
  def foo(self):
    # do something

  if __name__ == '__main__':
    # call foo

or without main:

class myClass:
  def foo(self):
    # do something

  # call foo

Right now I keep getting either the error that self is not defined, or the error that foo expects 1 argument but 0 was provided.

Xantium
  • 11,201
  • 10
  • 62
  • 89
bli00
  • 2,215
  • 2
  • 19
  • 46
  • 5
    You can't, because that doesn't make any sense. If you want `foo` to be callable without a `myClass` instance, why is it an instance method? – Aran-Fey Jun 29 '18 at 17:19
  • you can use `foo` as a `classmethod` to achieve this. – Soumendra Jun 29 '18 at 17:23
  • @Soumendra If the OP really wants to call the function from *inside* the class statement, there's no class yet either. (Strictly speaking, `foo` can be called immediately as a *regular* function, although providing the correct arguments may be problematic.) – chepner Jun 29 '18 at 17:58
  • @chepner, yeah, correct. I missed the indentation and thought OP try to call from outside of the class. Thanks. – Soumendra Jun 29 '18 at 18:07

2 Answers2

1

You cannot. The function is part of the class, so to access it you must access the class first.

class myClass:
    def foo(self):
        # do something

myClass().foo()

If you just don't want to type myClass().foo() but only foo then you could just return the myClass() in a new function called foo():

def foo():
    return  myClass().foo()

You can use self in a class when calling from inside the class itself:

class myClass:
    def __init__(self):
        pass
    def foo(self):
        pass
    def method2(self):
        self.foo()

This does not create a new instance of myClass like calling myClass().foo() would, and you do not need to pass the same arguments that you may have passed in myClass.

Xantium
  • 11,201
  • 10
  • 62
  • 89
0

Since foo() has a self parameter, that means it is an instance method, and therefore it is only callable from an instance of myClass.

If you want foo to be callable without an instance, use the @staticmethod decorator, and remove self from the parameter list.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • Technically, it's an instance method because it's a function defined in the body of a `class` statement and it isn't decorated by either `@classmethod` or `@staticmethod`; the `self` parameter just means the function is prepared to receive the argument it will be passed when called. – chepner Jun 29 '18 at 17:28
  • @chepner You're right of course, `self` is not a magical name. But in an effort to preserve my sanity, I'm deliberately ignoring any use of `self` outside of its widely accepted meaning. – John Gordon Jun 29 '18 at 17:42