python函数中可选参数的命名实践 [英] Naming practice for optional argument in python function

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

问题描述

在python函数中为可选参数赋予与外部变量相同的名称是否可以? 由于下面定义的函数f和g给出相同的输出,因此似乎工作正常.但是,这是否被认为是不好的做法,并且在某些情况下会失败吗?

Is it OK to give the optional argument in a python function the same name as an outside variable? It seems to work fine as functions f and g defined below give the same output. However, is this considered bad practice and does it fail in some cases?

a = 1
def f(x,A=a): return x*A
def g(x,a=a): return x*a

print g(2)
>> 2
print g(2,a=2)
>> 4

推荐答案

它可以工作,尽管很容易让人感到困惑,但这是完全有效的.这是由于以下事实:该函数和对该函数的调用发生在不同的名称空间中.因此,如果您写:

It will work, allthough it can easily be a bit confusing, it is perfectly valid. This is due to the fact that the function and the call to the function happen in different namespaces. So if you write:

def some_function(var1,var2=somevalue):  #var1 & var2 of functions namespace
    some things happening here

var1 = somevalue #mainspace var1
var2 = somevalue #mainspace var2
some_function(var1,var2=var2) 
#upper line: first var2 = from function, second var2 = from mainspace 

它将起作用,因为主命名空间中的var1是与函数命名空间中的var1完全不同的变量.而且,即使您似乎在一行中两次使用了var2,某些函数的调用也将按所示工作.但是正如您在解释困难时所看到的那样,这样做会引起一些混乱,因此,如果可以的话,最好跳过这样的事情.与其他某些语言相比,Python的主要优点之一是它的可读性,您应该通过自己的编码风格来支持它.

it will work, as var1 in the main namespace is an entirely different variable than var1 in the functions namespace. And the call of somefunction will work as shown, even if you -seemingly- use var2 twice in one line. But as you can see in the difficulties while explaining, there is some confusion arised by doing this, so better skip things like that if you can. One of Pythons main advantages over some other languages is it's readability, you should support that through your coding style.

命名变量a和其他变量A也是您应该避免的事情.在此处阅读有关pyhton中的命名约定的信息:www.python.org/doc/essays/styleguide.html,并在此处阅读有关名称空间的信息:

And naming variables a and other variables A is something you should avoid too. Have a read about naming conventions in pyhton here: www.python.org/doc/essays/styleguide.html and a read about namespaces here: http://bytebaker.com/2008/07/30/python-namespaces/

这篇关于python函数中可选参数的命名实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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