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 write the code for using _ _ init__ and _ _ new__

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article shows you how to write the code for the use of _ _ init__ and _ _ new__, the content is concise and easy to understand, and it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

The code is as follows:

# 011. Briefly describe the difference between _ _ new__ and _ _ init__ in object-oriented

# _ _ init__ is called when the instance object is created, and then sets some initial values of the object properties.

# _ _ new__ is called before the instance is created, because its task is to create the instance and return it, which is a static method.

Class Book: def _ new__ (cls, title): if not hasattr (cls, "_ ins"): cls._ins=super (). _ new__ (cls) print ('in _ new__') return cls._ins

Def _ init__ (self, title): print ('in _ init__') super (). _ init__ () self.title = title

If _ _ name__ ='_ main__': b = Book ('The Spider Book') b2 = Book (' The Flask Book') print (id (b)) print (id (b2) print (b.title) print (b2.title))

# that is, _ _ new__ is called before _ _ init__, and the return value of _ _ new__ (instance) # will be passed to the first parameter of the _ _ init__ method, and then _ _ init__ will set some parameters to the instance, that is, how to write the code for the use of _ _ init__ and _ _ new__. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are 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

Internet Technology

Wechat

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

12
Report