How to use Python metaclass to implement singleton pattern
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!