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 相关文章推荐
python写的ARP攻击代码实例
Jun 04 Python
Python压缩解压缩zip文件及破解zip文件密码的方法
Nov 04 Python
Python中scatter函数参数及用法详解
Nov 08 Python
Java及python正则表达式详解
Dec 27 Python
深入理解Python 关于supper 的 用法和原理
Feb 28 Python
详解python Todo清单实战
Nov 01 Python
Python+PyQT5的子线程更新UI界面的实例
Jun 14 Python
Python中调用其他程序的方式详解
Aug 06 Python
python matplotlib折线图样式实现过程
Nov 04 Python
TensorFlow学习之分布式的TensorFlow运行环境
Feb 05 Python
Tensorflow:转置函数 transpose的使用详解
Feb 11 Python
使用Python画了一棵圣诞树的实例代码
Nov 27 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 压缩文件夹的类代码
2009/11/05 PHP
php 8小时时间差的解决方法小结
2009/12/22 PHP
Yii2.0中的COOKIE和SESSION用法
2016/08/12 PHP
jQuery学习基础知识小结
2010/11/25 Javascript
Javascript创建自定义对象 创建Object实例添加属性和方法
2012/06/04 Javascript
jQuery事件之键盘事件(ctrl+Enter回车键提交表单等)
2014/05/11 Javascript
javascript中对象的定义、使用以及对象和原型链操作小结
2016/12/14 Javascript
JavaScript脚本语言是什么_动力节点Java学院整理
2017/06/26 Javascript
JS库中的Particles.js在vue上的运用案例分析
2017/09/13 Javascript
微信小程使用swiper组件实现图片轮播切换显示功能【附源码下载】
2017/12/12 Javascript
react以create-react-app为基础创建项目
2018/03/14 Javascript
Vue中android4.4不兼容问题的解决方法
2018/09/04 Javascript
图文讲解vue的v-if使用方法
2019/02/11 Javascript
vue项目中使用fetch的实现方法
2019/04/25 Javascript
js中复选框的取值及赋值示例详解
2020/10/18 Javascript
element中table高度自适应的实现
2020/10/21 Javascript
javascript实现前端分页功能
2020/11/26 Javascript
Python引用(import)文件夹下的py文件的方法
2014/08/26 Python
Python实现的弹球小游戏示例
2017/08/01 Python
numpy自动生成数组详解
2017/12/15 Python
python3实现指定目录下文件sha256及文件大小统计
2019/02/25 Python
Python坐标线性插值应用实现
2019/11/13 Python
Django restframework 框架认证、权限、限流用法示例
2019/12/21 Python
tensorflow获取预训练模型某层参数并赋值到当前网络指定层方式
2020/01/24 Python
Python迭代器协议及for循环工作机制详解
2020/07/14 Python
python 下载文件的几种方法汇总
2021/01/06 Python
python 写一个水果忍者游戏
2021/01/13 Python
美国批发零售网站:GearXS
2016/07/26 全球购物
医学专业大学生求职信
2014/07/12 职场文书
销售人才自我评价范文
2014/09/27 职场文书
水知道答案观后感
2015/06/08 职场文书
党员证明模板
2015/06/19 职场文书
追讨欠款律师函
2015/06/24 职场文书
详解Vue slot插槽
2021/11/20 Vue.js
Netflix《海贼王》真人版剧集多张片场照曝光
2022/04/04 日漫
Windows server 2012 配置Telnet以及用法详解
2022/04/28 Servers