Metaclass

one. Definition
We know that an instance will be generated after the class is instantiated, that is to say, the instance is generated by the class. But since everything is an object in python, what is the class made of?
In python, we define:
a metaclass is a class of a class, which is a template for generating a class;
an instance of a metaclass is a class, and type is a built-in metaclass of python, which is used to directly control the generated class. In python Any class defined by a class is an object created by instantiating the type class. Don't ask me, which class is the type class produced by....
II. Two ways to define a class
Way 1: Use the class keyword to define the
Metaclass
way 2: Use the type metaclass to define
Metaclass
this part of the code block as follows:
#Class definition way 1, use the class keyword

class School:
    def __init__(self,name,addr):
        self.name = name
        self.addr = addr

    def showinfo(self):
        print("%s学校在%s"%(self.name,self.addr))
# print(School.__name__)
# print(School.__dict__)

#类的定义方式二,使用type元类定义
def __init__(self,name,addr):
    self.name = name
    self.addr = addr
def showinfo(self):
    print("%s学校在%s"%(self.name,self.addr))
    #type函数三个参数,第一个参数是类名,字符串格式;第二个参数是它所继承的类,元组形式;第三个参数是它的属性字典,字典形式,可以是数据属性也可以是函数属性
TSchool = type('School',(object,),{'__init__':__init__,'showinfo':showinfo,'size':32000})
print(TSchool.__name__)
print(TSchool.__dict__)
tschool = TSchool('浙江大学','浙江省杭州市')      #实例化
print(tschool.size) #查看数据属性size
tschool.showinfo()  #调用类的showinfo方法

three. Custom metaclass
We know that the metaclass of all unspecified classes is type, and all classes inherit the type metaclass.
Metaclass

Guess you like

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