python3 类型作为函数参数

python3 types as function arguments

是否可以像下面的示例那样将类型作为函数参数传递?

def test(*args):
    '''decorator implementation with asserts'''
    ...


@test(str, int)
def fn1(ma_chaine, mon_entier):
    return ma_chaine * mon_entier

@test(int, int)
def fn2(nb1, nb2):
    return nb1 * nb2

或者我应该将它们作为字符串传递(例如 @test('str', 'int))并在内部测试函数中将它们与 ifelif 一起使用?

有效吗?

def test(obj, typ):
    if isinstance(obj, typ):
        print('Type Matches')
        return True
    return False

test('mystring', str)

"Type Matches"

是的。

你应该这样做吗?

Probably not

And some more information of type checking

Python 函数的参数不关心它的类型。

您可以传递任何类型的参数,并可以检查参数的类型。

很简单,您可以检查得到的参数类型。

尝试

def fn1(ma_chaine, mon_entier):
    if type(ma_chaine) == int && type(mon_entier) == int:
        return ma_chaine * mon_entier
    else:
        raise TypeError("Arguments should be 'int' type. Got '{}' type and '{}' type.".format(type(ma_chaine), type(mon_entier))