侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python中metaclass原理与用法详解

Python  /  管理员 发布于 7年前   294

本文实例讲述了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 moduleclass 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: Falseprint hasattr(Foo, 'BAR')# Out: Truef = Foo()print f.BAR# Out: 'bip'

现在用一个类来处理

# remember that `type` is actually a class like `str` and `int`# so you can inherit from itclass 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数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》

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


  • 上一条:
    python实现websocket的客户端压力测试
    下一条:
    python实现接口并发测试脚本
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客