Python中的函数参数类型 [英] Function parameter types in Python

查看:151
本文介绍了Python中的函数参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除非我弄错了,否则在Python中创建函数的工作方式如下所示:

Unless I'm mistaken, creating a function in Python works like this:

def my_func(param1, param2):
    # stuff

然而,实际上并没有给出这些参数的类型。另外,如果我还记得,Python是一种强类型语言,因此Python看起来不应该让你传入一个不同于函数创建者期望类型的参数。但是,Python如何知道函数的用户正在传递适当的类型?如果程序是错误的类型,程序是否会死亡,假设函数实际使用参数?你必须指定类型吗?

However, you don't actually give the types of those parameters. Also, if I remember, Python is a strongly typed language, as such, it seems like Python shouldn't let you pass in a parameter of a different type than the function creator expected. However, how does Python know that the user of the function is passing in the proper types? Will the program just die if it's the wrong type, assuming the function actually uses the parameter? Do you have to specify the type?

推荐答案

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

Python is strongly typed because every object has a type, every object knows its type, it's impossible to accidentally or deliberately use an object of a type "as if" it was an object of a different type, and all elementary operations on the object are delegated to its type.

这与名称无关。 Python中的 name 不具有类型:if和when名称的定义,名称引用对象对象 >确实有一个类型(但实际上并不强制在名称上输入一个类型:名称是一个名称)。

This has nothing to do with names. A name in Python doesn't "have a type": if and when a name's defined, the name refers to an object, and the object does have a type (but that doesn't in fact force a type on the name: a name is a name).

A Python中的名称可以很好地在不同的时间引用不同的对象(就像在大多数编程语言中一样,尽管不是全部) - 并且对名称没有限制,如果它曾经引用过类型X的对象,那么永远只能引用其他类型为X的对象。名称上的约束不是强类型概念的一部分,尽管一些静态键入的爱好者(其中名称​​ do 受到约束,并且以静态的AKA编译时间方式)也会这样滥用该术语。

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.

这篇关于Python中的函数参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆