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__方法,那 ...
随机推荐
- 我的开发框架(WinForm)2
上篇文章简单的介绍了一下,我的一个开发框架.看的人还不少,多谢大家的关注,我继续介绍一下,模块和模块之间是怎么组织起来的. Data模块: 该模块主要完成对数据的操作,采用仓储模式实现,在核心模块(C ...
- WebService地址变成计算机名的解决办法
WCF 4.0 has solved this issue in some instances with a new config option that use Request Headers: & ...
- 关于Eclipse中配置产品启动的插件
比较省事的是白哥给我一个配置文件(EE_CONF_TEST.launch),使用的方法白哥推荐我新建一个普通的java项目,然后拷贝到这个项目中. 拷贝到项目中之后在Run Configuration ...
- jemter接口测试之---接口测试的一些约定
一.接口规范 1.前端请求接口 请求数据格式:appType =1&args ={json}&session =xxx×tamp =now&sign =x ...
- 【转】web测试方法总结
一.输入框 1.字符型输入框: (1)字符型输入框:英文全角.英文半角.数字.空或者空格.特殊字符“~!@#¥%……&*?[]{}”特别要注意单引号和&符号.禁止直接输入特殊字符时 ...
- PM2 管理nodejs项目
pm2 是一个带有负载均衡功能的Node应用的进程管理器. 当你要把你的独立代码利用全部的服务器上的所有CPU,并保证进程永远都活着,0秒的重载, PM2是完美的. 它非常适合IaaS结构,但不要把它 ...
- 搭建maven开发环境测试Hadoop组件HDFS文件系统的一些命令
1.PC已经安装Eclipse Software,测试平台windows10及Centos6.8虚拟机 2.新建maven project 3.打开pom.xml,maven工程项目的pom文件加载以 ...
- Web前端发展简史
Web前端发展简史 有人说“前端开发”是IT界最容易被误解的岗位,这不是空穴来风.如果你还认为前端只是从美工那里拿到切图, JS和CSS一番乱炖,难搞的功能就去网上信手拈来,CtrlC + Ctrl ...
- 谈谈asp.net中的<% %>,<%= %>,<%# %><%$ %>的使用
学而不思则罔,思而不学则殆,每天坚持一小步,则成功一大步 asp.net中的<% %>,<%= %>,<%#eval("") %><%$ ...
- ios Trace xcode buile count
前言: 1.记录xcode编辑次数很有必要,特别是在频繁发版本时和根据现有编译次数记录估算工期时间很有帮助 2.全部自动化处理,告别手动时代 正文: 1.新建工程或者现有工程里设置: 然后设置xcod ...