面试题答案
一键面试def debug_decorator(func):
def wrapper(*args, **kwargs):
print(f'Entering method {func.__name__}')
result = func(*args, **kwargs)
print(f'Exiting method {func.__name__}')
return result
return wrapper
def add_debug_to_methods(cls):
for name, method in cls.__dict__.items():
if callable(method) and not name.startswith('__'):
setattr(cls, name, debug_decorator(method))
return cls
class DebugMeta(type):
def __new__(mcs, name, bases, namespace):
new_cls = super().__new__(mcs, name, bases, namespace)
return add_debug_to_methods(new_cls)
# 示例使用
class MyClass(metaclass=DebugMeta):
def my_method(self):
print('Inside my_method')
obj = MyClass()
obj.my_method()
上述代码实现步骤如下:
- 定义
debug_decorator
装饰器,用于在方法执行前后打印调试信息。 - 定义
add_debug_to_methods
函数,它遍历类的所有属性,对实例方法应用debug_decorator
装饰器。 - 定义
DebugMeta
元类,在__new__
方法中创建类对象后,调用add_debug_to_methods
函数为类的实例方法添加调试装饰器。 - 通过
MyClass
类展示如何使用这个元类,创建MyClass
的实例并调用my_method
方法时,会看到调试信息的打印。