Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Python metaclass to implement singleton pattern

Shulou Source: shulou.com Published: 2022-06-01 02:13:46 09月21日 Update

This article mainly introduces how to use Python metaclass to achieve singleton pattern, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Metaclass implementation: class MetaClass (type): def _ call__ (self, * args, * * kwargs): "self: class Singleton"if not hasattr (self," ins "): insObject = super (_ class__, self). _ call__ (* args, * * kwargs) setattr (self," ins ", insObject) return getattr (self) "ins") class Singleton (object, metaclass=MetaClass): passif _ _ name__ = = "_ _ main__": ins = Singleton () print (id (ins)) ins = Singleton () print (id (ins)) Thank you for reading this article carefully I hope the article "how to use Python metaclass to achieve singleton pattern" shared by the editor is helpful to everyone. At the same time, I also hope that you can support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Articles patterns values interests at the same time more friends knowledge editing industry information information channels channels reference learning help support Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Redmi MariaDB Apple Shulou Technology