class mymetaclass(type):
def __init__(self,a,b,c):
print('run')
print('a',a)
print('b',b)
print('c',c)
print('self=%s' % self)
class A(metaclass=mymetaclass):
def __init__(self,name):
self.name = name
print('self.name = %s'%self.name)
obj = A('test')
返回值:
run
a A
b ()
c {‘module’: ‘main’, ‘qualname’: ‘A’, ‘init’: <function A.init at 0x0000020216CBA158>}
self=<class ‘main.A’>
self.name = test
结论:元类中的init 方法要比当前类中的提前执行
class Metal(type):
def __init__(self,cls_name,base,namespace):
if not cls_name.istitle():
raise TypeError('类名必须大写开头')
else:
print('类实例化成功')
#命名方式 大驼峰
class person(metaclass=Metal): #如果改成Person 则不会报错
pass
Traceback (most recent call last):
File “C:/Users/Jonathan/Desktop/元类.py”, line 83, in
class person(metaclass=Metal):
File “C:/Users/Jonathan/Desktop/元类.py”, line 79, in init
raise TypeError(‘类名必须大写开头’)
TypeError: 类名必须大写开头
结论:元类的作用是对当前类的创建(声明,并非实例化)做出一些限制。