Python属性、方法和类管理系列之----元类
元类的介绍
请看位于下面网址的一篇文章,写的相当好。
http://blog.jobbole.com/21351/
实例补充
class Meta(type):
def __new__(meta, cls, parent, attr_dict):
res = super(Meta, meta).__new__(meta,cls, parent, attr_dict)
print('meta new stage, %s is %s, %s is %s' % (meta, type(meta), cls, type(cls)))
return res
def __init__(self,cls, parent, attr_dict):
super(Meta, self).__init__(cls,parent, attr_dict)
print('meta init stage, %s is %s, %s is %s' % (self, type(self), cls, type(cls)))
def __call__(self, *args, **kargs):
print('meta call stage, %s is %s' % (self, type(self)))
return super(Meta, self).__call__(*args, **kargs)
def decorate(cls):
print('decorate cls, %s is %s' % (cls, type(cls)))
return cls
@decorate
class A(metaclass=Meta):
def __new__(cls):
res = super(A, cls).__new__(cls)
print('A new stage, %s is %s' % (cls, type(cls)))
return res
def __init__(self):
super(A, self).__init__()
print('A init stage, %s is %s' % (self, type(self)))
def test(self):
pass
a=A()
print(a)
运行结果如下:
meta new stage, <class '__main__.Meta'> is <class 'type'>, A is <class 'str'>
meta init stage, <class '__main__.A'> is <class '__main__.Meta'>, A is <class 'str'>
decorate cls, <class '__main__.A'> is <class '__main__.Meta'>
meta call stage, <class '__main__.A'> is <class '__main__.Meta'>
A new stage, <class '__main__.A'> is <class '__main__.Meta'>
A init stage, <__main__.A object at 0x00000000022A74E0> is <class '__main__.A'>
<__main__.A object at 0x00000000022A74E0>
说明:
当我们自己创建一个类时,其实Python内部的运作机制如下:
- 看这个类中是否有设置元类,如果有,调用该元类进行初始化,如果没有,调用type进行初始化。
- 无论是我们自己定义的元类还是type,都有一个
__new__方法,用来生成元类, 都有一个__init__用来初始化类。 - 查看是否有类的装饰器,如果有的话,调用之。
其实,元类的__new__和__init__几乎什么都不做。
当我们创建一个类的实例时,其实Python内部的运作机制如下: - 调用元类的
__call__方法,该方法会做两件事情:
- 调用类自身的
__new__方法用来创建类(如果有的话),如果我们没有显示的定义它,那么会调用从object继承过来的__new__方法。 - 调用类自身的
__init__方法(如果有的话)来初始化得到实例,如果我们没有显示的定义它,那么会调用从object继承过来的__init__方法。
其实,object的__init__几乎什么都不做。
应用实例
由于我们经常在写类的内置拦截器方法时,少写下划线,或者出现拼写错误,从而怎么调试都不能发现问题所在,在浪费了很多时间以后才发现时犯的是多么低级的错误。
下面我写了这个元类来进行检查。
class AttrCheckMeta(type):
def __new__(meta, cls, parent, attr_dict):
import types
attrs_checking_list=['__init__', '__del__', '__call__', '__str__', '__repr__',
'__getattr__', '__setattr__', '__delattr__', '__getattribute__',
'__getitem__', '__setitem__', '__delitem__', '__iter__', '__next__',
'__contains__', '__get__', '__set__', '__delete__', '__lt__',
'__le__', '__gt__', '__ge__', '__eq__', '__add__', '__iadd__',
'__radd__', '__sub__', '__isub__', '__rsub__', '__mul__', '__imul__',
'__neg__', '__pos__', '__abs__', '__floordiv__', '__ifloordiv__',
'__truediv__', '__itruediv__', '__mod__', '__imod__', '__imod__',
'__pow__', '__ipow__', '__concat__', '__iconcat__', '__and__',
'__iand__', '__or__', '__ior__', '__xor__', '__ixor__', '__inv__',
'__invert__ ', '__lshift__', '__ilshift__', '__rshift__', '__irshift__ ',
'__bool__', '__len__', '__nonzero__', '__enter__', '__exit__',
'__new__', '__index__', '__oct__', '__hex__']
for attr,value in attr_dict.items():
#处理方法名前后都包含__,但是名字写错的情况。
if attr[:2]=='__' and attr[-2:]=='__' and isinstance(value, types.FunctionType):
if attr not in attrs_checking_list:
print('found problem function: %s' % attr)
#处理漏写后面__的情况,此时Python会把这个方法吗当成是需要扩张的方法。
elif attr.startswith('_'+cls+'__') and isinstance(value, types.FunctionType):
print('maybe has problem: %s' % attr)
return super(AttrCheckMeta, meta).__new__(meta,cls, parent, attr_dict)
def __init__(self,cls, parent, attr_dict):
super(AttrCheckMeta, self).__init__(cls,parent, attr_dict)
def __call__(self, *args, **kargs):
return super(AttrCheckMeta, self).__call__(*args, **kargs)
class A(metaclass=AttrCheckMeta):
def __new__(cls):
return super(A, cls).__new__(cls)
def __add(self, va, val):
pass
def __innit__(self):
super(A, self).__init__()
a=A()
故意写了两个错误在类A中,运行结果如下:
found problem function name: __innit__
maybe has problem: _A__add
当然,这个可以用装饰器来完成同样的任务,而且装饰器似乎更加直白、容易理解。
代码如下:
def check_ol(cls):
'''the overloading function name is easily to have spelling mistake.
It will be very hard to find the related mistakes, so i use this automethod to check
It will print the possible mistakes once found, will do nothing if passed'''
import types
attrs_checking_list=['__init__', '__del__', '__call__', '__str__', '__repr__',
'__getattr__', '__setattr__', '__delattr__', '__getattribute__',
'__getitem__', '__setitem__', '__delitem__', '__iter__', '__next__',
'__contains__', '__get__', '__set__', '__delete__', '__lt__',
'__le__', '__gt__', '__ge__', '__eq__', '__add__', '__iadd__',
'__radd__', '__sub__', '__isub__', '__rsub__', '__mul__', '__imul__',
'__neg__', '__pos__', '__abs__', '__floordiv__', '__ifloordiv__',
'__truediv__', '__itruediv__', '__mod__', '__imod__', '__imod__',
'__pow__', '__ipow__', '__concat__', '__iconcat__', '__and__',
'__iand__', '__or__', '__ior__', '__xor__', '__ixor__', '__inv__',
'__invert__ ', '__lshift__', '__ilshift__', '__rshift__', '__irshift__ ',
'__bool__', '__len__', '__nonzero__', '__enter__', '__exit__',
'__new__', '__index__', '__oct__', '__hex__']
for attr,value in cls.__dict__.items():
#处理方法名前后都包含__,但是名字写错的情况。
if attr[:2]=='__' and attr[-2:]=='__' and isinstance(value, types.FunctionType):
if attr not in attrs_checking_list:
print('found problem function name: %s' % attr)
#处理漏写后面__的情况,此时Python会把这个方法吗当成是需要扩张的方法。
elif attr.startswith('_'+cls.__name__+'__') and isinstance(value, types.FunctionType):
print('maybe has problem: %s' % attr)
return cls
Python属性、方法和类管理系列之----元类的更多相关文章
- python day 11: 类的补充,元类,魔法方法,异常处理
目录 python day 11 1. 类的补充 1.1 通过反射来查找类,创建对象,设置对象的属性与方法 1.2 类的魔法方法:getitem,setitem 1.3 元类__metaclass__ ...
- Python属性、方法和类管理系列之----属性初探
在学习dict的时候,肯定听过dict是Python中最重要的数据类型,但是不一定知道为什么.马上你就会明白原因了. Python中从模块.到函数.到类.到元类,其实主要管理方法就是靠一个一个的字典. ...
- 类装饰器,元类,垃圾回收GC,内建属性、内建方法,集合,functools模块,常见模块
'''''''''类装饰器'''class Test(): def __init__(self,func): print('---初始化---') print('func name is %s'%fu ...
- Python 属性方法、类方法、静态方法、 特殊属性__doc__ (内建属性)
总结:和类的关联性讲:属性方法>类方法>静态方法 属性方法@property:仅仅是调用方式不用+括号. 类方法@classmethod:访问不了累的属性变量,只可以访问类变量. 静态方法 ...
- Python 爬取各大代理IP网站(元类封装)
import requests from pyquery import PyQuery as pq base_headers = { 'User-Agent': 'Mozilla/5.0 (Windo ...
- Python说文解字_详解元类
1.深入理解一切接对象: 1.1 什么是类和对象? 首先明白元类之前要明白什么叫做类.类是面向对象object oriented programming的重要概念.在面向对象中类和对象是最基本的两个概 ...
- Python元类实战,通过元类实现数据库ORM框架
本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是Python专题的第19篇文章,我们一起来用元类实现一个简易的ORM数据库框架. 本文主要是受到了廖雪峰老师Python3入门教程的启 ...
- Delphi 类引用 Class Reference 元类 MetaClass 用法
delphi中类引用的使用实例 类引用类引用(Class Reference)是一种数据类型,有时又称为元类(MetaClass),是类的类型的引用.类引用的定义形式如下: class of type ...
- Python属性、方法和类管理系列之----描述符类
什么是描述符类? 根据鸭子模型理论,只要具有__get__方法的类就是描述符类. 如果一个类中具有__get__和__set__两个方法,那么就是数据描述符,. 如果一个类中只有__get__方法,那 ...
随机推荐
- 用指令修改DOM
对于HTML5,input元素有autofocus这个属性,用户在第一次进入界面时就可以和用户交互,对于浏览器来说,可以 把键盘焦点定位在某个元素上,但是对于非input元素,则不可以,我们可以使用指 ...
- 什么是CS和BS结构,两种结构的区别
什么是CS和BS结构,两种结构的区别 什么是C/S和B/S结构? C/S又称Client/Server或客户/服务器模式.服务器通常采用高性能的PC.工作站或小型机,并采用大型数据库系 ...
- Android屏幕保持唤醒状态
我们程序偶尔会有需要屏幕一直或较长时间的保持唤醒状态,而用户的睡眠时间又设置的比较短.这时可能会对程序以及用户的使用造成一定的影响.在Android中有两种方法,可以让我们在我们需要保持唤醒的页面长时 ...
- Open Flash Chart在php中的使用教程
http://www.cnblogs.com/huangcong/archive/2013/01/27/2878650.html 为了画一个漂亮的表格,我从网上找到了OpenFlashChart(of ...
- 错误源:WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).
Server Error in '/' Application. WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping ...
- [转]十年前的老文:以 Linux 的名义
一.灰姑娘的狂欢 今年初,林纳斯·托瓦兹承认:“如果在12年前,有人告诉我Linux会发展到今天的模样,我肯定会惊得目瞪口呆.” 托瓦兹说的是实话.1991年,这名21岁的芬兰赫尔辛基大学的学生,偶然 ...
- HTML <input> 标签的 type 属性
HTML <input> 标签的 type 属性 HTML <input> 标签 实例 下面的表单拥有两个输入字段以及一个提交按钮: <form action=" ...
- 测试中的几个case
一.页面上对引起 大量数据提交的 按钮/链接 点击一次后, disable 需求: 对于重要的表单.数量庞大/响应慢的系统,在做提交时, 又有页面还在loading状态, 此时连续做两次点击, 经常 ...
- 【转】querystring传递中文出现乱码的问题
原帖地址:http://www.cnblogs.com/Fly-sky/archive/2009/04/22/1441015.html 现象:近期项目中用到查询字符串传值,如果传递的是英文一切正常,但 ...
- 九度OJ 1348 数组中的逆序对 -- 归并排序
题目地址:http://ac.jobdu.com/problem.php?pid=1348 题目描述: 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对.输入一个数组,求 ...