Object-oriented - the creation process of classes 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 class name __new__ is to create the object cls represents foo
 14          return  object .__new__(cls, *args, ** kwargs)
 15  # Phase 1: The interpreter executes the code from top to bottom to create the Foo class
 16  # Phase 2: Creates the obj object from the Foo class
 17 obj = Foo()

flow chart:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325635303&siteId=291194637