首页 »Python » rubymetaclass:python aop (metaclass) »正文
rubymetaclass:python aop (metaclass)
来源: 发布时间:星期三, 2009年9月2日 浏览:56次 评论:0
代码可以直接运行 看结果 如果命令调试 python -m pdb pyaop.py (Pdb)b pyaop:10 (Pdb)c (Pdb)n .....自己来把 调试参考 : python pdb 基础调试 源文件 : pyaop.py #!/usr/bin/python
# -*- coding: utf8 -*-
# 参考:http://www.cnblogs.com/Alexander-Lee/archive/2008/12/06/pythonaop.html
"""
py aop 代理类 ( meta 特性 )
由于使用 __meta__ = <type 'type'>
pyaop 继承 type
"""
pyaop(type):
# before ; after 思路方法变量引用声明
beforeop=lambda e : None
afterop=lambda e : None
#思路方法(静态思路方法)
@method
def before(self,func):
pyaop.beforeop=func
@method
def after(self,func):
pyaop.afterop=func
""" 使用调试
# python -m pdb pyaop.py
# 由下面 A类 < __meta__ = pyaop >
# 类 ____ 指向 pyaop ____
#
# (Pdb)b pyaop:36 (大概就是下面form types 行号)
# (Pdb)a (可以看看调试中各参数值注意dict为A对象传过来了)
# mcl = < '____.pyaop'>
# name = A
# bases = (<type 'object'>,)
# dict = {'__module__': '____', 'foo': <function foo at 0x7fddced4>, '__meta__': < '____.pyaop'>, 'foo2': <function foo2 at 0x7fddcf0c>}
# 本目: 使用 新另个对象挂载 被aop后 A对象 思路方法
"""
def ____(mcl,name,bases,dict):
from types import FunctionType
obj=object
def aop(func):
def wrapper(*args, **kwds):
pyaop.beforeop(obj)
value = func(*args, **kwds)
pyaop.afterop(obj)
value
wrapper
#添加代理
for attr, value in dict.iteritems:
isinstance(value, FunctionType):
dict[attr] = aop(value)
#挂载到 obj 上
obj=super(pyaop, mcl).____(mcl, name, bases, dict)
obj
A(object):
#被 aop 代理 声明!
__meta__ = pyaop
def foo(self):
total = 0
for i in range(100000):
total = total+1
pr total
def foo2(self):
from time import sleep
total = 0
for i in range(100000):
total = total+1
#sleep(0.0001)
pr total
"""#####################################################################################
# 测试
#####################################################################################"""
def beforep(self):
pr('before')
def afterp(self):
pr('after')
__name__ "____":
pyaop.before(beforep)
pyaop.after(afterp)
a=A
a.foo
a.foo2
相关文章
读者评论
发表评论
|
|