Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the override _ _ new__ method in python

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

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!

Tags: Method object content article reference initiative value interest writing parameters examples guys partners more source code knowledge space results industry interpreter Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Redmi vpn Linux Huawei