Calling a class function without triggering the __init__

Viewed 12626

Is there any way to call functions inside a class without triggering the __init__ part of that class? Let's say I have the next class, usually I'd call the function this way:

class Potato():
    def __init__(self):
        print("Initializing")
    def myfunction(self):
        print("I do something")

Potato().myfunction()

But as expected that prints the Initializing part. Now, If I wanted to call myfunction without triggering that. How would you do it? Pros and cons of doing it? It's even possible?

4 Answers

I know this was posted a while ago, but worth mentioning that a class method without "self" can be invoked without calling the constructor with () and with no init. Not really adding anything new but I think it answers the question simply.

>>> class Yolo:
...     def notify(data):
...         print(f"some data: {data}")
...
>>>
>>> Yolo.notify({1:1})
some data: {1: 1}
>>>

and

>>> class Yolo:
...     @staticmethod
...     def notify(data):
...         print(f"some data: {data}")
...
>>> Yolo.notify({1:1})
some data: {1: 1}

Compared with

>>> class Yolo:
...    def __init__(self):
...       print("init")
...    def notify(data):
...       print(f"some data: {data}")
...
>>>
>>> Yolo.notify({1:1})
some data: {1:1}
>>> Yolo()
init
Related