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 use the override _ _ new__ method in python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces how to use the rewrite _ _ new__ method in python. It is very detailed and has a certain reference value. Friends who are interested must finish it!

1. Overriding the _ _ new__ method must be returnsuper (). _ _ new__ (cls).

If the class inherits only the object class, it can also be replaced with object._new__ (cls), which is not recommended.

Otherwise, if Python's interpreter does not refer to the object that allocates space, the object's initialization method will not be called.

2. _ _ new__ is a static method (see source code), and you need to actively transfer cls parameters when calling.

Example

Class MusicPlayer (object): def _ new__ (cls, * args, * * kwargs): # if no result is returned, return super (). _ new__ (cls) def _ _ init__ (self): print ("initialize the music playback object") player = MusicPlayer () print (player) above is all the content of the article "how to rewrite the _ _ new__ method 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