这很具有挑战性,但我认为我做到了!我的代码并不是非常复杂,但你需要对元类非常了解。
元类和包装器(WarnIfNotCalled.py):
class Notifier:
def __init__(self, name, obj, callback):
self.callback = callback
self.name = name
self.obj = obj
self.called = False
def __call__(self, *args, **kwargs):
self.callback(self.obj, *args, **kwargs)
self.called = True
def __del__(self):
if not self.called:
print("Warning! {} function hasn't been called!".format(self.name))
class WarnIfNotCalled(type):
def __new__(cls, name, bases, dct):
dct_func = {}
for name, val in dct.copy().items():
if name.startswith('__') or not callable(val):
continue
else:
dct_func[name] = val
del dct[name]
def getattr(self, name):
if name in dct_func:
return Notifier(name, self, dct_func[name])
dct['__getattr__'] = getattr
return super(WarnIfNotCalled, cls).__new__(cls, name, bases, dct)
使用起来非常简单 - 只需要指定一个元类即可
from WarnIfNotCalled import WarnIfNotCalled
class A(metaclass = WarnIfNotCalled):
def foo(self):
print("foo has been called")
def bar(self, x):
print("bar has been called and x =", x)
如果您没有忘记调用这些函数,一切都会像往常一样正常工作。
a = A()
a.foo()
a.bar(5)
输出:
foo has been called
bar has been called and x = 5
但是如果您确实忘记了:
a = A()
a.foo
a.bar
你看到以下内容:
Warning! foo function hasn't been called!
Warning! bar function hasn't been called!
愉快地进行调试吧!