一、什么是元类

二、如何使用元类

(一)不依赖class关键字创建一个自定义类

(二)自定义元类控制类的产生

(三)自定义元类控制类的调用

一、什么是元类

在python中,一切皆对象,而对象都是由类实例化得到的。所以类也是对象,而类的类就是元类,其实 type 就是元类。

二、如何使用元类

class Teacher:
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def score(self):
print('%s is scoring' %self.name) tea1=Teacher('egon',18,'male')
print(type(tea1)) #<class '__main__.Teacher'>
print(type(Teacher)) #<class 'type'>
print(Teacher) #<class '__main__.Teacher'> 对象tea1是调用Teacher类得到的,如果说一切皆对象,那么Teacher也是一个对象,
只要是对象,都是调用一个类实例化得到的,即Teacher=元类(...),内置的元类是type

类与元类的关系:

  1. 调用元类---->自定义的类
  2. 调用自定义的类---->自定义的对象

class关键字创建自定义类的底层的工作原理,分为四步

  1. 先拿到类名:'Teacher'
  2. 再拿到类的基类们:(object,)
  3. 然后拿到类的名称空间(执行类体代码,将产生的名字放到类的名称空间也就是一个字典里,)
  4. 调用元类实例化得到自定义的类: Teacher=type('Teacher',(object,),{...})

自定义类的三个关键组成部分:

  1. 类名
  2. 类的基类们
  3. 类的名称空间

1、不依赖class关键字创建一个自定义类

创建之前需要了解一下exec函数

exec: 是一个python内置函数,可以将字符串的代码添加到局部名称空间中;

exec(字符串形式的代码, 全局名称空间, 局部名称空间)

#1. 拿到类名
class_name='Teacher'
#2. 拿到类的基类们:(object,)
class_bases=(object,)
#3. 拿到类的名称空间
class_dic={}
class_body="""
school = 'Qinghua' def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex def score(self):
print('%s is scoring' %self.name)
"""
exec(class_body,{},class_dic)
print(class_dic) #4.调用type得到自定义的类
Teacher=type(class_name,class_bases,class_dic)
print(Teacher) #<class '__main__.Teacher'> 跟用class定义的类一样 print(Teacher)
# print(Teacher.school)
# print(Teacher.score) tea1=Teacher('egon',18,'male')
print(tea1.__dict__)

2、自定义元类控制类的产生

模板:

#但凡继承了type的类才能称之为自定义的元类,否则就是只是一个普通的类
class Mymeta(type):
def __init__(self,class_name,class_bases,class_dic):
print(self) #self--->Teacher
print(class_name)
print(class_bases)
print(class_dic) #Teacher=Mymeta('Teacher',(object,),{...})
class Teacher(object,metaclass=Mymeta): #metaclas--->元类
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def score(self):
print('%s is scoring' %self.name)

控类的产生:

1.控制类名必须用驼峰体:
2.类体必须有文档注释
class Mymeta(type):
school = 'Qinghua'
def __init__(self,class_name,class_bases,class_dic):
if class_name.islower():
raise TypeError('类名必须使用驼峰体') doc = class_dic.get('__doc__') if doc is None:
raise TypeError('类体中必须有文档注释') #Teacher=Mymeta('Teacher',(object,),{...})
class Teacher(object,metaclass=Mymeta): #metaclas--->元类
school = 'Qinghua'
def __init__(self,name,age,sex): #self--->Teacher
self.name=name
self.age=age
self.sex=sex
def score(self):
print('%s is scoring' %self.name) print(Teacher.__dict__)

3、自定义元类控制类的调用

'''
class Mymeta(type): #但凡继承了type的类才能称之为自定义的元类,否则就是只是一个普通的类
pass class Teacher(object): #Teacher=Mymeta('Teacher',(object,),{...})
school = 'Qinghua' def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex def score(self):
print('%s is scoring' %self.name) def __call__(self, *args, **kwargs):
print(self)
print(args)
print(kwargs)
tea1=Teacher('egon',18,'male') tea1(1,2,a=1,b=2) #__call__(tea1,(1,2).{'a':1,'b':2})
''' 总结:对象之所以可以调用,是因为对象的类中有一个函数__call__ 推导:如果一切皆对象,那么Teacher也是一个对象,该对象之所可以调用,肯定是这个对象的类中也定义了一个函数__call__ class Mymeta(type): #但凡继承了type的类才能称之为自定义的元类,否则就是只是一个普通的类
def __call__(self, *args, **kwargs): #self=Teacher这个类,args=('egon',18,'male'),kwargs={}
# 1. 先产生一个空对象
tea_obj=self.__new__(self) #tea_obj是Teacher这个类的对象 self--->Teacher
# 2. 执行__init__方法,完成对象的初始属性操作
self.__init__(tea_obj,*args,**kwargs)
# 3. 返回初始化好的那个对象
return tea_obj class Teacher(object,metaclass=Mymeta): #Teacher=Mymeta('Teacher',(object,),{...})
school = 'Qinghua' #tea_obj,'egon',18,'male'
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex def score(self):
print('%s is scoring' %self.name) tea1=Teacher('egon',18,'male') # 会触发Teacher的类(即元类)中的__call__函数
print(tea1)
print(tea1.__dict__)

最新文章

  1. 火车头采集ecshop 文章接口文件
  2. Lucene.net站内搜索—6、站内搜索第二版
  3. C++复制对象时勿忘每一部分
  4. UI设计实战篇——利用Bootstrap框架制作查询页面的界面
  5. 64位系统下注册32位dll文件
  6. MySQL日期和时间函数
  7. Gradle templates 的使用
  8. 委托与Lambda表达式
  9. 【IOS实例小计】图像移动--可扩展为动态实现图标变化
  10. Quick Cocos2dx Action相关
  11. Codeforces 839C Journey【DFS】
  12. 谈一谈java里面的反射机制
  13. Web、OAuth2/SSO相关拾遗
  14. .py文件右键添加Edit with IDLE
  15. python学习笔记——urllib库中的parse
  16. redis的setbit命令
  17. [LeetCode] 711. Number of Distinct Islands II_hard tag: DFS
  18. 【环境配置】配置ndk
  19. ZT Linux系统环境下的Socket编程详细解析
  20. latex 三个不同的图放在一行且每个图都有注释

热门文章

  1. MapReduce数据流-概述
  2. 亿级消息系统的核心存储:Tablestore发布Timeline 2.0模型
  3. 3331: [BeiJing2013]压力
  4. html实体字符转换成字符串
  5. 梯度优化算法Adam
  6. hdu 2892 area (圆与多边形交面积)
  7. 系统学习前端之FormData详解
  8. CSS引入的方式有哪些? link和@import的区别是?
  9. H3C PAP验证
  10. codeforces 616D