python 元类型编程,实现匿名验证器的装饰器AuthenticationDecoratorMeta
2012-12-24 20:03
691 查看
metaclass,元类
metaclass是这样定义的:In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances.metaclass的实例化结果是类,而class实例化的结果是instance。metaclass是创建类的模板,所有的类都是通过他来create的(调用__new__),你可以定创建类的独特行为,实现你所需要的特殊功能。
type 也是metalclass的一种元类。
通过派生type的子类,来实现类创建过程中的特殊行为。
type的构造函数:type.__new__(cls, name, bases, dct)
cls: 将要创建的类,类似与self,但是self指向的是instance,而这里cls指向的是class
name: 类的名字
bases: 基类,通常是tuple类型
attrs: dict类型,就是类的属性或者函数
实现为类的方法,进行匿名验证的metaclass, ----AuthenticationDecoratorMeta
源码:
from types import FunctionType def Authentication(func): print 'Execute validition Successfully!' return func class AuthenticationDecoratorMeta(type): def __new__(cls, name, bases, dct): for name, value in dct.iteritems(): if name not in ('__metaclass__', '__init__', '__module__') and \ type(value) == FunctionType: value = Authentication(value) dct[name] = value return type.__new__(cls, name, bases, dct) class Login(object): __metaclass__ = AuthenticationDecoratorMeta def Delete(self, x): print 'Delete ', x def main(): login = Login() login.Delete('xxxx') if __name__ == '__main__': main()
运行效果如下:
Execute validition Successfully! Delete xxxx
相关文章推荐
- python 元类型编程, 单例模式SingleTon的一种实现方式
- 【Python】使用装饰器为Python实现运行时类型检查
- python学习系列之python装饰器基础(4)---装饰器实现token验证功能
- python 元类型编程,实现方法级的时间性能记录(performanceCount)
- Java编程实现验证哥德巴赫猜想
- VC++下对匿名管道的编程实现
- Python入门笔记之装饰器decorator
- 23种设计模式之装饰器模式(结构型,2 Decorator,c++实现)
- Python 学习笔记9(装饰器,decorator)
- 字符型图片验证码识别完整过程及Python实现
- python之利用PIL库实现页面的图片验证码及缩略图 推荐
- jquery实现上传文件大小类型的验证
- python扩展实现方法--python与c混和编程
- python实现Decorator模式
- Python Qt GUI快速编程-第四章的计算器python3+pytq5+Qt Designer实现
- 详细Python修饰器Decorator的函数式编程
- 结构型模式之装饰模式(Decorator Pattern)C++实现
- RabbitMQ(python实现)学习之三:Routing(接收端接收固定类型消息)
- Python的函数机制与装饰器实现
- 【python网络编程】利用select实现socket全双工异步通信