你想要的都可以通过使用装饰器来完成。
我可以通过要求对象具有构造函数或要求类型为类或内置类型来实现类似的功能
首先定义一个装饰器(一个做你想做的事情的函数,让你在调用之前处理参数或对函数做任何你想做的事情)
def decorator(function):
def wrapper(*args, **kwargs): # the function that does the checks
# you can do the same for any keyword arguments
for argument in args:
if hasattr(argument, "__init__"):
print(f'Argument {argument} has an __init__ method')
return function(*args, **kwargs)
return wrapper
然后你可以将它应用到任何函数中
@decorator
def myFunction(some_argument):
return None
例如,如果您使用int 调用myFunction,您将获得以下信息
In [18]: myFunction(3)
Argument 3 has an __init__ method
我可以像这样使用 Python 的类型系统吗? ... 这样以下是该函数的有效用法。
您可以在装饰器内部检查 __anotations__ 中传递的函数的 this 问题并验证每个输入。 __anotations__ 返回一个字典,用键指定变量的名称和类型注释的值。一个简单的例子是
def decorator(function):
def wrapper(*args, **kwargs):
# {'a': <class 'str'>, 'b': <class 'int'>}
type_hints = function.__annotations__
# kwargs is a dictionary so
# if a and b are parameters whose values are hello and
# 2 then the dict is {a: "hello", b: 2}
for keyword in kwargs:
assert type(kwargs.get(keyword)) == type_hints.get(keyword)
# also check on the list args
for index, argument in enumerate(args):
assert type(argument) == type_hints[list(type_hints)[index]]
return function(*args, **kwargs)
return wrapper
@decorator
def myFunc(a: str, b: int):
return a, b
现在您可以按如下方式调用该函数,并且仅当类型提示与每个函数参数的类型匹配时它才会起作用
In [42]: myFunc("hello", 1)
Out[42]: ('hello', 1)
In [43]: myFunc(1, 2)
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-43-8bd42ff057a5> in <module>
----> 1 myFunc(1, 2)
# ... the rest of the traceback