如何在动态类型语言(即Python)中指定参数类型?

发布于 2024-09-24 08:09:34 字数 120 浏览 3 评论 0原文

有 Java 的等价物吗

String myMethod (MyClass argument) {...}

Python 中

?谢谢你,托马斯

Is there any such equivalent of Java

String myMethod (MyClass argument) {...}

in Python?

Thank you, Tomas

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

淡忘如思 2024-10-01 08:09:34

否。(还有更多内容将其四舍五入到 15 个字符......)

No. (And more stuff to round this up to 15 characters...)

很酷不放纵 2024-10-01 08:09:34

不,没有。

事实上,检查类型被认为是“非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.

不知在何时 2024-10-01 08:09:34

Python 3.x 有函数注释,您可以在其中声明参数和返回类型:

def myMethod(argument: MyClass) -> str:
   ...

但目前 Python 对它们不执行任何操作,它们仅用作文档。

Python 3.x has function annotations where you can declare argument and return types:

def myMethod(argument: MyClass) -> str:
   ...

But currently Python does nothing with them, they serve as documentation only.

仅一夜美梦 2024-10-01 08:09:34

我只是想说,我完全同意类型检查是邪恶的。但 python 也非常灵活,我很想变得邪恶。这段代码将在运行时生效,而不是在编译时生效。您可以对返回类型执行类似的操作。像这样的东西对于调试可能很有用,而且因为它是一个装饰器,所以很容易删除。

为了使其对调试有用,您必须遇到两种类型具有正在访问的所有相同属性但具有不同语义的情况。所以这是一个相当有限的案例。除此之外,当此代码运行时,您无论如何都会遇到打字错误。好消息是这几乎从来都不是问题。我真的不知道为什么静态类型语言的人们对此如此重视。

def types(*args, **kwargs):
    arg_types = args
    kwarg_types = kwargs
    def decorator(f):
        def func(*args, **kwargs):
            for arg, arg_type in zip(args, arg_types):
                if not isinstance(arg, arg_type):
                    raise TypeError("Wrong type suckah")
            for kw, arg in kwargs.items():
                if not isinstance(arg, kwarg_types[kw]):
                    raise TypeError("this is a bad error message")
            return f(*args, **kwargs)
        return func
    return decorator

@types(int, str, bool, flag=bool)
def demo(i, strng, flag=False):
    print i, strng, flag

demo(1, "foo", True)

try:
    demo("foo", "bar", flag="foobar")
except TypeError:
    print "busted on posargs"

try:
    demo(1, "foo", flag=2)
except TypeError:
    print "busted on keyargs"

try:
    demo(1, "foo", 3)
except TypeError:
    print "no use sneaking it through"

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.

def types(*args, **kwargs):
    arg_types = args
    kwarg_types = kwargs
    def decorator(f):
        def func(*args, **kwargs):
            for arg, arg_type in zip(args, arg_types):
                if not isinstance(arg, arg_type):
                    raise TypeError("Wrong type suckah")
            for kw, arg in kwargs.items():
                if not isinstance(arg, kwarg_types[kw]):
                    raise TypeError("this is a bad error message")
            return f(*args, **kwargs)
        return func
    return decorator

@types(int, str, bool, flag=bool)
def demo(i, strng, flag=False):
    print i, strng, flag

demo(1, "foo", True)

try:
    demo("foo", "bar", flag="foobar")
except TypeError:
    print "busted on posargs"

try:
    demo(1, "foo", flag=2)
except TypeError:
    print "busted on keyargs"

try:
    demo(1, "foo", 3)
except TypeError:
    print "no use sneaking it through"
丢了幸福的猪 2024-10-01 08:09:34

没有。

在Python中,它是程序的
使用内置的责任
类似 isinstance() 和
issubclass() 测试变量类型
并正确使用。 Python 试图
在给你的同时不妨碍你
实现强类型所需的一切
检查。

来自 为什么Python 是一种动态语言,也是一种强类型语言。还

在动态类型语言中,
变量只是一个绑定到 a 的值
姓名;该值有一个类型——比如
“整数”或“字符串”或“列表”——但是
变量本身没有。你可以
有一个变量,现在,
持有一个号码,然后分配一个
如果您需要更改它,则将字符串添加到它。

此外, isinstance() 和 issubclass() 可用于进行类型检查。如果你想确保参数是 MyClass 类型,你可以在函数内部进行检查。您甚至可以对参数的值进行类型转换(如果您有接受此类值的构造函数)并将其分配给 my_object。

No.

In Python, it's the program's
responsibility to use built-in
functions like isinstance() and
issubclass() to test variable types
and correct usage. Python tries to
stay out of your way while giving you
all you need to implement strong type
checking.

from Why is Python a dynamic language and also a strongly typed language. Also

In a dynamically typed language, a
variable is simply a value bound to a
name; the value has a type -- like
"integer" or "string" or "list" -- but
the variable itself doesn't. You could
have a variable which, right now,
holds a number, and later assign a
string to it if you need it to change.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文