面试题答案
一键面试1. 装饰器实现方法拦截和行为增强
装饰器本质上是一个函数,它可以接受一个函数作为参数,并返回一个新的函数。这个新函数可以在原函数执行前后添加额外的逻辑,从而实现方法拦截和行为增强。
def method_decorator(func):
def wrapper(*args, **kwargs):
print(f"Before calling {func.__name__}")
result = func(*args, **kwargs)
print(f"After calling {func.__name__}")
return result
return wrapper
2. 元类控制类的创建过程
元类是类的类,它控制着类的创建过程。我们可以定义一个元类,在创建类时自动将特定装饰器应用到类的某些方法上。
class MetaClass(type):
def __new__(cls, name, bases, attrs):
for attr_name, attr_value in attrs.items():
if callable(attr_value) and attr_name.startswith('specific_'):
attrs[attr_name] = method_decorator(attr_value)
return super().__new__(cls, name, bases, attrs)
3. 使用元类和装饰器协同工作
class MyClass(metaclass=MetaClass):
def general_method(self):
print("This is a general method")
def specific_method(self):
print("This is a specific method")
obj = MyClass()
obj.general_method()
obj.specific_method()
在上述代码中:
method_decorator
是一个普通的装饰器,它在被装饰函数执行前后打印一些信息,实现了方法拦截和行为增强。MetaClass
是一个元类,在创建类时,它遍历类的属性,如果属性是可调用的(即方法)并且方法名以specific_
开头,就将method_decorator
装饰器应用到该方法上。MyClass
使用MetaClass
作为元类,这样在创建MyClass
时,其specific_method
方法会自动被method_decorator
装饰,而general_method
不受影响。运行代码时,调用specific_method
会看到装饰器添加的额外行为,而调用general_method
则不会。