简体   繁体   中英

Python call __init__() method only one time

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?

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

There's no direct way to disable __init__ , but there are a few ways to work around this. One of them is having a flag:

class Class:
    _init_already = False
    __init__(self):
        if not Class._init_already:
            ...
            Class._init_already = True

But this is ugly. What is it that you are really trying to accomplish?

You shouldn't put anything in __init__() that you only want to run once. Each time you create an instance of a class __init__() will be run.

If you want to customize the creation of your class you should look into creating a metaclass . Basically, this lets you define a function that is only run once when the class is first defined.

The init method will always be called however you could create another method called run() or something, that you call after creating the object, optionally.

foo = ClassName()
foo.run() # replacement for __init__

foo2 = ClassName()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM