Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to initialize and execute once in python

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report