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__方法,那 ...
随机推荐
- C语言内存管理
作用域: 1.代码块儿作用域: 注意的是:这里面{}就代表一个代码块儿,里面的东西是独立的,不可被其他地方访问的. 2.函数作用域 3.文件作用域 先提一下 在当前有一个文件,main.c 还有一个文 ...
- Linux shell之数组
引言 在Linux平台上工作,我们经常需要使用shell来编写一些有用.有意义的脚本程序.有时,会经常使用shell数组.那么,shell中的数组是怎么表现的呢,又是怎么定义的呢?接下来逐一的进行讲解 ...
- Vim 的补全模式加速器,轻松玩转全部 15 种自动补全模式
1. 关于 Vim 补全模式 ---- Vim 一共提供了 15 种自动补全的模式(:help ins-completion).其中有两种的补全列表内容与另外两种相同,只是排序不同,这 15 种 ...
- 【转载】TCL装载包和版本控制
转载来源:http://blog.chinaunix.net/uid-9967220-id-3033702.html package forget ?package package ...? ...
- QL Server 中四种匹配符的含义
SQL中我们会见到很多的匹配符,下面解释一下 % 代表零个或者多个任意字符 _ 代表一个任意字符 [] 指定范围内的任意单个字符 [^] 不在指定范围内的任意单个字符 带有匹配符的字符串必须使用引号引 ...
- java程序执行顺序
原来自己一直都没弄明白Java程序的执行顺序问题,今天,自己写了个测试,果然与自己考虑的有差距 测试代码: 一个父类Animal 一个子类Dog 测试类Test 运行结果: 所以执行顺序是: 父类An ...
- sql server中分布式查询随笔
由于业务逻辑的多样性 经常得在sql server中查询不同数据库中数据 这就产生了分布式查询的需求 现我将开发中遇到的几种查询总结如下: 1.access版本 --建立连接服务器 exec sp_a ...
- wpf打印控件 实现分页打印控件功能
因为 要实现打印 wpf listbox控件 数据特别多 要打印在 几张纸上 找了几天 都没有找到相关的例子 现在 解决了 在这里和大家分享一下 public void print(Fram ...
- WCF编程系列(二)了解WCF
WCF编程系列(二)了解WCF 面向服务 服务是复用进化的结果,起初的复用是函数,面向对象编程的出现使复用从函数上升到对象,随后面向组件编程又将复用从对象上升到组件,现在面向服务编程将复用 ...
- Java线程间通信--生产者消费者
class ProducerConsumerDemo { public static void main(String[] args) { Resource r = new ...