python中metaclass原理与用法详解


Posted in Python onJune 25, 2019

本文实例讲述了python中metaclass原理与用法。分享给大家供大家参考,具体如下:

什么是 metaclass.

metaclass (元类)就是用来创建类的类。在前面一篇文章《python动态创建类》里我们提到过,可以用如下的一个观点来理解什么是metaclass:

MyClass = MetaClass()
MyObject = MyClass()

metaclass是python 里面的编程魔法

同时在前面一篇《python动态创建类》文章里描述动态创建class 的时候介绍了type,他允许你用如下的方法创建一个类:

MyClass = type('MyClass', (), {})

其根本原因就在于 type 就是一个 metaclass, python利用type在后面创建各种各样的类。搞不明白的是,为什么是 "type" 而不是 "Type",可能考虑到 str 是用来创建字符串的,int 是用来 创建整形对象,所以type 用来创建 class object的,都用小写好了。

在python中的任何东西都是对象。包括int,str,function,class等。他们都是从一个class  创建的,我们可以通过查看 __class__ 属性来检查.

>>> age = 35
>>> age.__class__
<type 'int'>
>>> name = 'bob'
>>> name.__class__
<type 'str'>
>>> def foo(): pass
>>> foo.__class__
<type 'function'>
>>> class Bar(object): pass
>>> b = Bar()
>>> b.__class__
<class '__main__.Bar'>

检查__class__属性

>>> a.__class__.__class__
<type 'type'>
>>> age.__class__.__class__
<type 'type'>
>>> foo.__class__.__class__
<type 'type'>
>>> b.__class__.__class__
<type 'type'>

发现什么了,结果都是 "type", 其实  type 就是python内置的一个metaclass.当然,你可以创建自己的metaclass. 这里有一个很重要的属性:

__metaclass__ 属性

当你在写一个class的时候,你可以加入__metaclass__属性.

class Foo(object):
 __metaclass__ = something...
 [...]

如果你这么做了,那么python 将调用 metaclass 去创建 Foo class, 感觉是不是让你有点困惑呢。

python 将在你的class定义中查找__metaclass__,如果找到,就会用这个metaclass去创建Foo class,如果没有找到,就会用 type 去创建class.如果上篇文章提到的一样.所以,当你

class Foo(Bar):
 pass

pyton 将会如下去解析:是否有__metaclass__ 在Foo 里面,如果是的,则用metaclass  去创建一个名字为 ”Foo" 的class object. 如果没有找到,则看其基类Bar里面是否有__metaclass__,如果基类没有,则看所在的module 层是否有__metaclass__,如果都没有的话,则调用 type 去创建这个类。

现在的问题是,__metaclass__ 里面到底能做什么?结论是:能创建一个class的东西。什么能创建一个class, 其实就是 type,或者type 的子类(subclass)。

自定义 metaclass

metaclass的主要目的就是在创建类的时候,做一些自动的改变。比如,打个不恰当的比方,我们打算将一个module里所有类的属性都变成大写的。其中一种处理办法就是用 __metaclass__(申明在module上).

我们打算利用 metaclass 把所有的属性变成大写的。__metaclass__并不一定要求是一个class, 是一个可以调用的方法也是可以的。我们就从一个简单的例子看起

def upper_attr(future_class_name, future_class_parents, future_class_attr):
 """
  Return a class object, with the list of its attribute turned
  into uppercase. """
 # pick up any attribute that doesn't start with '__'
 attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
 # turn them into uppercase
 uppercase_attr = dict((name.upper(), value) for name, value in attrs)
 # let `type` do the class creation
 return type(future_class_name, future_class_parents, uppercase_attr)
__metaclass__ = upper_attr # this will affect all classes in the module
class Foo(): # global __metaclass__ won't work with "object" though
 # but we can define __metaclass__ here instead to affect only this class
 # and this will work with "object" childrend
 bar = 'bip'
print hasattr(Foo, 'bar')
# Out: False
print hasattr(Foo, 'BAR')
# Out: True
f = Foo()
print f.BAR
# Out: 'bip'

现在用一个类来处理

# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type):
  # __new__ is the method called before __init__
  # it's the method that creates the object and returns it
  # while __init__ just initializes the object passed as parameter
  # you rarely use __new__, except when you want to control how the object
  # is created.
  # here the created object is the class, and we want to customize it
  # so we override __new__
  # you can do some stuff in __init__ too if you wish
  # some advanced use involves overriding __call__ as well, but we won't
  # see this
  def __new__(upperattr_metaclass, future_class_name,
        future_class_parents, future_class_attr):
    attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
    uppercase_attr = dict((name.upper(), value) for name, value in attrs)
    return type(future_class_name, future_class_parents, uppercase_attr)

显然这不是很oop的做法,直接调用了type方法,而不是调用父类的__new__方法,下面这么做:

class UpperAttrMetaclass(type):
  def __new__(upperattr_metaclass, future_class_name,
        future_class_parents, future_class_attr):
    attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
    uppercase_attr = dict((name.upper(), value) for name, value in attrs)
    # reuse the type.__new__ method
    # this is basic OOP, nothing magic in there
    return type.__new__(upperattr_metaclass, future_class_name,
              future_class_parents, uppercase_attr)

你可能注意到 upperattr_metaclass ,这其实就相于self,普通类方法里的self.一个更通用的方法如下:

class UpperAttrMetaclass(type):
  def __new__(cls, name, bases, dct):
    attrs = ((name, value) for name, value in dct.items() if not name.startswith('__'))
    uppercase_attr = dict((name.upper(), value) for name, value in attrs)
    return super(UpperAttrMetaclass, cls).__new__(cls, name, bases, uppercase_attr)

通过上面的例子可以了解metaclass了,也了解了在__init__方法,__new__方法里去做一个hook.当然还可以在__call__里面做文章,但更多的人喜欢在__init__里面修改 。

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Pyramid添加Middleware的方法实例
Nov 27 Python
python查找目录下指定扩展名的文件实例
Apr 01 Python
python Django批量导入不重复数据
Mar 25 Python
Python实现返回数组中第i小元素的方法示例
Dec 04 Python
Python运维之获取系统CPU信息的实现方法
Jun 11 Python
Python 移动光标位置的方法
Jan 20 Python
使用 Django Highcharts 实现数据可视化过程解析
Jul 31 Python
python并发编程 Process对象的其他属性方法join方法详解
Aug 20 Python
Pytorch在dataloader类中设置shuffle的随机数种子方式
Jan 14 Python
python如何基于redis实现ip代理池
Jan 17 Python
django实现HttpResponse返回json数据为中文
Mar 27 Python
在Django中使用MQTT的方法
May 10 Python
python实现接口并发测试脚本
Jun 25 #Python
Python实现EXCEL表格的排序功能示例
Jun 25 #Python
python实现动态创建类的方法分析
Jun 25 #Python
python pandas写入excel文件的方法示例
Jun 25 #Python
python多线程http压力测试脚本
Jun 25 #Python
Pyqt5 基本界面组件之inputDialog的使用
Jun 25 #Python
对PyQt5的输入对话框使用(QInputDialog)详解
Jun 25 #Python
You might like
PHP中通过HTTP_USER_AGENT判断是否为手机移动终端的函数代码
2013/02/14 PHP
腾讯微博提示missing parameter errorcode 102 错误的解决方法
2014/12/22 PHP
反射调用private方法实践(php、java)
2015/12/21 PHP
laravel 中如何使用ajax和vue总结
2017/08/16 PHP
PHP安全之register_globals的on和off的区别
2020/07/23 PHP
XML+XSL 与 HTML 两种方案的结合
2007/04/22 Javascript
JAVASCRIPT IE 与 FF中兼容问题小结
2009/02/18 Javascript
点弹代码 点击页面任何位置都可以弹出页面效果代码
2012/09/17 Javascript
如何用js控制frame的隐藏或显示的解决办法
2013/03/20 Javascript
js/html光标定位的实现代码
2013/09/23 Javascript
设置checkbox为只读(readOnly)的两种方式
2013/10/11 Javascript
JS关闭窗口与JS关闭页面的几种方法小结
2013/12/17 Javascript
多种方法实现load加载完成后把图片一次性显示出来
2014/02/19 Javascript
基于jQuery实现的双11天猫拆红包抽奖效果
2015/12/01 Javascript
深入解析AngularJS框架中$scope的作用与生命周期
2016/03/05 Javascript
JavaScript+Java实现HTML页面转为PDF文件保存的方法
2016/05/30 Javascript
ES6生成器用法实例分析
2017/04/10 Javascript
微信小程序获取用户openId的实现方法
2017/05/23 Javascript
最新Javascript程序员面试试题和解题方法
2017/11/23 Javascript
vue-router中scrollBehavior的巧妙用法
2018/07/09 Javascript
jQuery实现验证用户登录
2019/12/10 jQuery
Django应用程序中如何发送电子邮件详解
2017/02/04 Python
python与php实现分割文件代码
2017/03/06 Python
python数据预处理之将类别数据转换为数值的方法
2017/07/05 Python
python实现word 2007文档转换为pdf文件
2018/03/15 Python
Python使用gRPC传输协议教程
2018/10/16 Python
Python matplotlib画图与中文设置操作实例分析
2019/04/23 Python
Python pip安装第三方库实现过程解析
2020/07/09 Python
Pandas中DataFrame基本函数整理(小结)
2020/07/20 Python
安装python依赖包psycopg2来调用postgresql的操作
2021/01/01 Python
Pyside2中嵌入Matplotlib的绘图的实现
2021/02/22 Python
英文翻译的自我评价语句
2013/10/04 职场文书
医院护士见习期自我鉴定
2014/09/15 职场文书
护士医德考评自我评价
2015/03/03 职场文书
会计试用期自我评价
2015/03/10 职场文书
简短的人生哲理(38句)
2019/08/13 职场文书