Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python call __init__() method only one time

Tags:

python

init

Is there any way to call the init() method of a class only one time. Or how can I disable calling of init() when I create an object from a class?

like image 869
İlker Dağlı Avatar asked Dec 30 '25 14:12

İlker Dağlı


1 Answers

If you want a singleton, where there is only ever one instance of a class then you can create a decorator like the following as gotten from PEP18:

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    pass

Try it out:

>>> a = MyClass()
>>> b = MyClass()
>>> a == b
True
like image 67
Matt Williamson Avatar answered Jan 02 '26 07:01

Matt Williamson