我的問題是,我正在使用一個元類來包裝某些類的方法在一個計時器記錄的目的。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