本文由我司收集整编,推荐下载,如有疑问,请与我司联系
如何确保
Python
中的参数类型正确?
如何确保
Python
中的参数类型正确?
[
英
]How
do
I
ensure
parameter
is
correct
type in Python? I’m new to Python, and am trying to figure out if there is a way to specify
the variable type in a parameter definition. For example:
我是
Python
的新手,我想弄清楚是否有办法在参数定义中指定变量类型。例如:
def function(int(integer)) as opposed to:
而不是:
def function(integer) int(integer) I know it’s not a major difference, but I’m trying to
use good programming practices here, and if I’m defining a function with a large number
of parameters, it could get messy.
我知道这不是一个主要的区别,但我试图在这里使用良好的编程实践,如果我定
义一个具有大量参数的函数,它可能会变得混乱。
10
Python
uses
Duck
typing
which
means
you
should
not
discriminate
objects
based
on
what type they are, but based on what attributes and functions they have. This has many
advantages which are outside of the scope of this answer.
Python
使用
Duck
类型,这意味着您不应该根据它们的类型来区分对象,而是基
于它们具有的属性和功能。这具有许多优点,这些优点超出了本答案的范围。
What you should do instead if you want to add documentation to your function is to use
a docstring
如果要向函数添加文档,则应该使用文档字符串
def square(x): “““takes a number and squares it”““ return x**2 and type hints
并键入提示
def square(x: int) - int: “““takes a number and squares it”““ return x**2 if you really
need to check the arguments given to you, you can do a hasattr() to check for the attributes
and
functions
the
argument
provides.
In
most
situations
(including
this
one)
just
not