Python:方法中对象类型的注释

2024-09-24 20:37:00 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
How to check arguments of the function?

可能这是重复的问题。。对不起。。在

让我们看看下面的例子:

class ClassA(object):
     pass
class ClassB(object):
     pass

def foo(a, b):
    if not isinstance(a, ClassA):
         raise ValueError("1st agrument should be instance of ClassA")
    if not isinstance(b, ClassB):
         raise ValueError("2nd agrument should be instance of ClassB")
    print(a)
    print(b)

2.7python中是否有注释,或者__future__模块中有什么注释来注释检查输入变量的方法?在

写那些if not isinstance让我非常生气:D


Tags: ofinstanceifobjectnotpassbeclass
1条回答
网友
1楼 · 发布于 2024-09-24 20:37:00

没有内置的方法来定义函数的参数类型(这部分是通过设计实现的),而不是在传递classB时得到“预期的classA”错误,而是在查找属性时得到一个错误。然后可以在类B上定义这个属性,该函数将使用它最初设计的类型。在

有那么大的,here is an example of how to write the decorator you're after。在

相关问题 更多 >