检查Python函数中传递的参数数量 [英] Check the number of parameters passed in Python function

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

问题描述

我是 Python 新手,想知道是否有一种简单的方法可以获取 Python 函数中传递的参数数量.

I'm new in Python and wants to know if there is a simple way to get amount of passed parameters in Python function.

a(1, 2, 3) ==>3
a(1, 2) ==>2

推荐答案

你可以使用 locals() 来做到这一点

You can do this by using locals()

重要的是要注意,这应该作为最终方法的第一步来完成.如果在您的方法中引入一个新变量,您将改变您的结果.因此,请确保按照以下方式进行操作:

It is important to note, that this should be done as ultimately, your first step in your method. If you introduce a new variable in your method, you will change your results. So make sure you follow it this way:

def a(a, b, c):
    # make this your first statement
    print(len(locals()))

如果你这样做了:

def a(a, b, c):
    z = 5
    print(len(locals()))

您最终会得到 4,这不符合您的预期结果.

You would end up getting 4, which would not be right for your expected results.

关于 locals()

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

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