面向对象————类的创建过程 metaclass

 1 # __author: Administrator
 2 # __date: 2018/5/7
 3 class MyType(type):
 4     def __init__(self, what, bases=None, dict=None):#self->foo类
 5         super(MyType, self).__init__(what, bases, dict)
 6     def __call__(self, *args, **kwargs):# 当对象()时直接调用 self->foo
 7         obj = self.__new__(self, *args, **kwargs)
 8         self.__init__(obj)
 9 
10 class Foo(object,metaclass=MyType):
11     def __init__(self, name):
12         self.name = name
13     def __new__(cls, *args, **kwargs):#cls 类名  __new__是创建对象   cls代表的就是foo
14         return object.__new__(cls, *args, **kwargs)
15 # 第一阶段:解释器从上到下执行代码创建Foo类
16 # 第二阶段:通过Foo类创建obj对象
17 obj = Foo()

流程图:

猜你喜欢

转载自www.cnblogs.com/janus1345/p/9003877.html