python中没有对参数指定类型_【IT专家】如何确保Python中的参数类型正确?

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

如何确保

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值