【发布时间】:2011-12-04 22:30:05
【问题描述】:
我的问题是我使用元类将某些类方法包装在计时器中以用于记录目的。
例如:
class MyMeta(type):
@staticmethod
def time_method(method):
def __wrapper(self, *args, **kwargs):
start = time.time()
result = method(self, *args, **kwargs)
finish = time.time()
sys.stdout.write('instancemethod %s took %0.3f s.\n' %(
method.__name__, (finish - start)))
return result
return __wrapper
def __new__(cls, name, bases, attrs):
for attr in ['__init__', 'run']:
if not attr in attrs:
continue
attrs[attr] = cls.time_method(attrs[attr])
return super(MetaBuilderModule, cls).__new__(cls, name, bases, attrs)
我遇到的问题是我的包装器为每个 '__init__' 运行,即使我真的只希望它用于我正在实例化的当前模块。任何想要计时的方法也是如此。我不希望在任何继承的方法上运行时间,除非它们没有被覆盖。
class MyClass0(object):
__metaclass__ = MyMeta
def __init__(self):
pass
def run(self):
sys.stdout.write('running')
return True
class MyClass1(MyClass0):
def __init__(self): # I want this timed
MyClass0.__init__(self) # But not this.
pass
''' I need the inherited 'run' to be timed. '''
我已经尝试了一些东西,但到目前为止我都没有成功。
【问题讨论】:
标签: python inheritance metaclass