我的问题是,我正在使用一个元类来包装某些类的方法在一个计时器记录的目的。Python __metaclass__继承问题
例如:
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. '''
我试过一些东西,但到目前为止我没有成功。
谢谢佩特,这工作完美。我非常接近我能够品尝到的答案。有时你需要另一双眼睛来理解我所猜测的疯狂。再次感谢! CB – theceebee