除非我弄错了,在Python中创建一个函数是这样的:

def my_func(param1, param2):
    # stuff

但是,实际上并没有给出这些参数的类型。而且,如果我没记错的话,Python是一种强类型语言,因此,Python似乎不应该让你传入与函数创建者期望的不同类型的参数。然而,Python如何知道函数的用户正在传递正确的类型呢?假设函数实际使用了形参,如果它是错误的类型,程序会死吗?必须指定类型吗?


当前回答

要有效地使用typing模块(Python 3.5新增),请包含all(*)。

from typing import *

你将准备使用:

List, Tuple, Set, Map - for list, tuple, set and map respectively.
Iterable - useful for generators.
Any - when it could be anything.
Union - when it could be anything within a specified set of types, as opposed to Any.
Optional - when it might be None. Shorthand for Union[T, None].
TypeVar - used with generics.
Callable - used primarily for functions, but could be used for other callables.

然而,你仍然可以使用类型名称,如int, list, dict,…

其他回答

从静态或编译时类型检查的意义上讲,Python不是强类型的。

大多数Python代码都属于所谓的“Duck Typing”——例如,你寻找一个对象上读取的方法——你不关心对象是磁盘上的文件还是套接字,你只想从中读取N个字节。

无论您是否指定类型提示,都将在运行时失败。

However, you can provide type hints for both function arguments and its return type. For example, def foo(bar: str) -> List[float] hints that bar is expected to be a string and the function returns a list of float values. This will result in a type check error when the method is invoked if the types don't match (before the use of the parameter in the function, or of the return type). This IMOHO is much more helpful in catching such errors vs an error about a missing field or method somewhere in the method call. I recommend reading the official Python documentation Typing - Support for type hints.

此外,如果使用类型提示,则可以使用静态类型检查器来验证代码的正确性。python中内置的一个这样的工具是myypy(官方文档)。关于静态类型检查的文章的这一部分很好地介绍了如何使用它。

要有效地使用typing模块(Python 3.5新增),请包含all(*)。

from typing import *

你将准备使用:

List, Tuple, Set, Map - for list, tuple, set and map respectively.
Iterable - useful for generators.
Any - when it could be anything.
Union - when it could be anything within a specified set of types, as opposed to Any.
Optional - when it might be None. Shorthand for Union[T, None].
TypeVar - used with generics.
Callable - used primarily for functions, but could be used for other callables.

然而,你仍然可以使用类型名称,如int, list, dict,…

在Python中,所有东西都有类型。如果参数类型支持,Python函数将执行它被要求执行的任何操作。

示例:foo将添加所有可以__add__ed;)的东西,而不太关心它的类型。这意味着,为了避免失败,你应该只提供那些支持加法的东西。

def foo(a,b):
    return a + b

class Bar(object):
    pass

class Zoo(object):
    def __add__(self, other):
        return 'zoom'

if __name__=='__main__':
    print foo(1, 2)
    print foo('james', 'bond')
    print foo(Zoo(), Zoo())
    print foo(Bar(), Bar()) # Should fail

Python是强类型的,因为每个对象都有一个类型,每个对象都知道它的类型,不可能意外或故意使用一个类型的对象,“好像”它是一个不同类型的对象,对象上的所有基本操作都委托给它的类型。

这和名字无关。Python中的名称没有“类型”:如果定义了名称,则名称指向对象,并且对象确实具有类型(但这实际上并不强制名称具有类型:名称就是名称)。

A name in Python can perfectly well refer to different objects at different times (as in most programming languages, though not all) -- and there is no constraint on the name such that, if it has once referred to an object of type X, it's then forevermore constrained to refer only to other objects of type X. Constraints on names are not part of the concept of "strong typing", though some enthusiasts of static typing (where names do get constrained, and in a static, AKA compile-time, fashion, too) do misuse the term this way.