What is the metaclass
Because everything is an object in python, it is actually a class of all objects.
And generating class class, called the metaclass, i.e. metaclass object instance of the class is
type metaclass is built, all classes (type including itself) are generated by the type instantiation. The inherited type of own class, also called the yuan class
How to find metaclass
print(type(dict)) #type
print(type(list)) #type
print(type(str)) #type
print(type(object)) #type
print(type(type)) #type
The underlying principle of class analysis
The underlying principle of class is actually passed several parameters let type to instantiate an object that is class.
#通过type来直接产生类,不用class关键字了
l={}
exec('''
school='oldboy'
def __init__(self,name):
self.name=name
def score(self):
print('分数是100')
''',{},l)
def __init__(self,name):
self.name=name
Person=type('Person',(object,),l)
print(Person.__bases__)
By generating custom classes to control the metaclass
#自定义元类;来控制类的产生:可以控制类名,可以控制类的继承父类,控制类的名称空间
# type
#自定义元类必须继承type,写一个类继承type 这种类都叫元类
class Mymeta(type):
# def __init__(self,*args,**kwargs):
def __init__(self,name,bases,dic):
# self 就是Person类
# print(name)
# print(bases)
# print(dic)
#练习一:加限制 控制类名必须以sb开头
# if not name.startswith('sb'):
# raise Exception('类名没有以sb开头')
#练习二:类必须加注释
print(self.__dict__['__doc__'])
#metaclass=Mymeta 指定这个类生成的时候,用自己写的Mymeta这个元类
class Person(object,metaclass=Mymeta):
'''
注释
'''
school='oldboy'
def __init__(self,name):
self.name=name
def score(self):
print('分数是100')
Custom calling process to control the metaclass class
#__call__
#控制类的调用过程,实际上在控制:对象的产生
class Mymeta(type):
def __call__(self, *args, **kwargs):
# print('xxx')
return 1
class Person(object,metaclass=Mymeta):
school='oldboy'
def __init__(self,name):
self.name=name
def score(self):
print('分数是100')
p=Person('nick')
print(p.name)
After the property has metaclass search order
#类的属性查找顺序:先从类本身中找--->mro继承关系去父类中找---->去自己定义的元类中找--->type中--->报错
#对象的属性查找顺序:先从对象自身找--->类中找--->mro继承关系去父类中找--->报错