Skip to content
New issue

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

什么是元类,请用代码解释如何使用元类 #96

Open
Sogrey opened this issue Feb 19, 2020 · 0 comments
Open

什么是元类,请用代码解释如何使用元类 #96

Sogrey opened this issue Feb 19, 2020 · 0 comments

Comments

@Sogrey
Copy link
Owner

Sogrey commented Feb 19, 2020

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

元类就是类的模板,可以自由控制创建类实例的过程。

@Sogrey Sogrey added this to 编程应用 in Python QAs Feb 19, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Python QAs
编程应用
Development

No branches or pull requests

1 participant