Get the App
SLTechnology News&Howtos  ›  Development  › 

How to initialize and execute once in python

Shulou Source: shulou.com Published: 2022-06-03 17:34:14 10月10日 Update

This article mainly introduces how to implement initialization in python, which is very detailed and has certain reference value. Friends who are interested must finish reading it.

1. Define whether the class attribute init_flag tag has been initialized.

The initial value is False.

2. Judge init_flag in the _ _ init__ method.

If it is False, initialize it.

3. Set init_flag to True.

When the _ _ init__ method is called automatically again, the initialization action will no longer be performed.

Example

Class MusicPlayer (object): # record the reference of the first created object instance = None # record whether the initialization action init_flag = False def _ _ new__ (cls, * args, * * kwargs): # 1. Determine whether the class attribute is an empty object if cls.instance is None: # 2. Call the method of the parent class and allocate the space cls.instance = super (). _ _ new__ (cls) # 3 for the first object. Return the object reference return cls.instance def _ _ init__ (self): if not MusicPlayer.init_flag: print ("initialize the music player") MusicPlayer.init_flag = True # create multiple objects player1 = MusicPlayer () print (player1) player2 = MusicPlayer () print (player2) above are all the contents of the article "how to initialize and execute once in python" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Objects properties methods content actions articles values interests again multiple instances guys buddies players more tags knowledge space industry information Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Tech Info Apple NVidia Huawei