We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
metaclass:元类,类似于创建类的模板,所有的类都是通过他来创建的,可以自由控制类的创建过程
单例模式、ORM模式
class Singleton(type): def __init__(self,*args,**kwargs): print('in __init__') self.__instance = None super(Singleton,self).__init__(*args,**kwargs) def __call__(self,*args,**kwargs): print('in __call__') if self.__instance is None: self.__instance = super(Singleton,self).__call__(*args,**kwargs) print(type(self.__instance)) return self.__instance class MyClass(metaclass=Singleton): pass my1 = MyClass() my2 = MyClass() print(my1 is my2)
運行結果:
>>> my1 = MyClass() in __call__ <class '__main__.MyClass'> >>> my2 = MyClass() in __call__ >>> print(my1 is my2) True
元类就是类的模板,可以自由控制创建类实例的过程。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
metaclass:元类,类似于创建类的模板,所有的类都是通过他来创建的,可以自由控制类的创建过程
单例模式、ORM模式
運行結果:
元类就是类的模板,可以自由控制创建类实例的过程。
The text was updated successfully, but these errors were encountered: