如何在动态类型语言(即Python)中指定参数类型?
有 Java 的等价物吗
String myMethod (MyClass argument) {...}
Python 中
?谢谢你,托马斯
Is there any such equivalent of Java
String myMethod (MyClass argument) {...}
in Python?
Thank you, Tomas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
否。(还有更多内容将其四舍五入到 15 个字符......)
No. (And more stuff to round this up to 15 characters...)
不,没有。
事实上,检查类型被认为是“非Pythonic”,因为任何看起来足够像预期类型的类型的对象都应该被同等对待。
No, there is not.
In fact, checking types is considered "un-Pythonic", because an object of any type that looks enough like the expected type should be treated equally.
Python 3.x 有函数注释,您可以在其中声明参数和返回类型:
但目前 Python 对它们不执行任何操作,它们仅用作文档。
Python 3.x has function annotations where you can declare argument and return types:
But currently Python does nothing with them, they serve as documentation only.
我只是想说,我完全同意类型检查是邪恶的。但 python 也非常灵活,我很想变得邪恶。这段代码将在运行时生效,而不是在编译时生效。您可以对返回类型执行类似的操作。像这样的东西对于调试可能很有用,而且因为它是一个装饰器,所以很容易删除。
为了使其对调试有用,您必须遇到两种类型具有正在访问的所有相同属性但具有不同语义的情况。所以这是一个相当有限的案例。除此之外,当此代码运行时,您无论如何都会遇到打字错误。好消息是这几乎从来都不是问题。我真的不知道为什么静态类型语言的人们对此如此重视。
I just want to say that I'm in full agreement that type checking is evil. But python is also incredibly flexible and I'm in the mood to be evil. This code will take effect at runtime and not compile time. You could do something similar for return type. Something like this could be useful for debugging and, because it's a decorator, it's easy enough to remove.
For it to be useful for debugging you would have to have a situation where two types had all the same attributes that were getting accessed but with different semantics. So that's a pretty limited case. Other than that, you're about to get a typerror anyways when this code runs. The good news is that this is almost never a problem. I really don't know why people from statically typed languages make such a big deal over it.
没有。
来自 为什么Python 是一种动态语言,也是一种强类型语言。还
此外, isinstance() 和 issubclass() 可用于进行类型检查。如果你想确保参数是 MyClass 类型,你可以在函数内部进行检查。您甚至可以对参数的值进行类型转换(如果您有接受此类值的构造函数)并将其分配给 my_object。
No.
from Why is Python a dynamic language and also a strongly typed language. Also
Further, isinstance() and issubclass() can be used to do type-checking. If you want to make sure that argument is of MyClass type, you can have a check inside the function. You can even type-cast the value of the argument (if you have a constructor accepting such value) and assign it to my_object.