是的,你可以使用metaclasses修改創作類的方法,和裝飾每一個功能有特殊裝飾。你的情況可能是這樣的:
#! /usr/bin/env python
#-*- coding:utf-8 -*-
import time
from inspect import isfunction
from functools import wraps
def sleep_decorator(func):
@wraps(func)
def inner(*args, **kwargs):
result = func(*args, **kwargs)
time.sleep(0.1)
return result
return inner
class BaseFoo(type):
def __new__(cls, name, bases, dct):
for name in dct:
if isfunction(dct[name]):
dct[name] = sleep_decorator(dct[name])
return type.__new__(cls, name, bases, dct)
class Foo (object):
__metaclass__ = BaseFoo
def __init__ (self, a, b):
self.a = a
self.b = b
def printer (self, arg):
print arg
+1 Metaclass在這裏矯枉過正 – 2012-08-06 11:03:01