在Python中,我们可以使用装饰器(Decorator)来包装函数并且保持输入和输出的相同类型信息。
下面是一个示例代码:
from functools import wraps
def preserve_type(func):
@wraps(func)
def wrapper(*args, **kwargs):
# 在函数执行前获取输入类型信息
input_type = type(args[0]) if args else type(kwargs.values()[0]) if kwargs else None
# 执行函数
result = func(*args, **kwargs)
# 在函数执行后获取输出类型信息
output_type = type(result)
# 输出类型与输入类型相同的信息
if input_type == output_type:
print("Input and output types are the same.")
return result
return wrapper
@preserve_type
def add(a, b):
return a + b
@preserve_type
def multiply(a, b):
return a * b
# 示例调用
print(add(1, 2)) # 输出: 3, Input and output types are the same.
print(multiply(2, 3)) # 输出: 6, Input and output types are the same.
在上述代码中,我们定义了一个名为preserve_type
的装饰器函数。它接受一个函数作为参数,并返回一个被包装的函数wrapper
。
wrapper
函数使用*args
和**kwargs
来接收任意数量和类型的参数,并在函数执行前获取输入类型信息。然后,它执行原始函数,并在函数执行后获取输出类型信息。最后,它比较输入类型和输出类型,并输出相应的信息。
在示例中,我们使用preserve_type
装饰器来包装add
和multiply
函数。当我们调用这些被包装的函数时,它们会打印输入和输出类型相同的信息。
这种方法可以确保函数的输入和输出类型保持一致,并集成到现有的函数中,而不需要显式地指定类型。