简体   繁体   English

对于不同功能的变量使用相同的名称?

[英]Using the same name for variables which are in different functions?

I've been searching a while for my question but haven't found anything of use. 我一直在寻找我的问题,但没有发现任何有用的东西。 My question is rather easy and straightforward. 我的问题相当简单明了。

Is it preferable or perhaps "pythonic" to use the same name for a certain variable which will appear in different functions, but with the same purpose? 对某个变量使用相同的名称是优选的还是“pythonic”,它将出现在不同的函数中,但具有相同的目的?

For example: 例如:

def first_function():
    pt = win.getMouse() # This waits for a mouseclick in a graphical window.

    if blabla.button.clicked(pt):
        second_function()

def second_function():
    pt = win.getMouse() 

    if whatever.button.clicked(pt):
        third_function()

Does it matter if the variable reference (pt) to win.getMouse() in the second_function() has the same name as the variable in the first_function() ? 如果win.getMouse()second_function()的变量引用(pt)与win.getMouse()中的变量同名,这first_function() Or should the variable pt in the second function be named something else? 或者第二个函数中的变量pt是否应该被命名为其他?

Names in functions are local ; 函数中的名称是本地的 ; reuse them as you see fit! 如你所愿,重复使用它们!

In other words, the names in one function have no relationship to names in another function. 换句话说,一个函数中的名称与另一个函数中的名称没有关系。 Use good, readable variable names and don't worry about names clashing. 使用良好,可读的变量名称,不要担心名称冲突。

Its not about "Pythonic" or not. 它不是关于“Pythonic”或不是。 In programming you always wish your variables to have a meaning, if the same name occures in differend functions that means they do things with the same purpose or same params. 在编程中,你总是希望你的变量具有意义,如果在差异函数中出现相同的名称,这意味着他们做的事情具有相同的目的或相同的参数。 Its fine to use same names in different functions, as long as they don't collide and make problems 只要它们不碰撞并产生问题,就可以在不同的功能中使用相同的名称

Variables defined in a function have Function Scope and are only visible in the body of the function. 函数中定义的变量具有函数范围 ,仅在函数中可见。

See: http://en.wikipedia.org/wiki/Scope_(computer_science)#Python for an explanation of Python's scoping rules. 请参阅: http//en.wikipedia.org/wiki/Scope_ (computer_science)#Python,了解Python的范围规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM