如何在Python中使用同名的命名参数和全局变量?

发布于 2024-09-13 08:40:36 字数 675 浏览 5 评论 0原文

模块中的示例代码:

somevar = "a"

def myfunc(somevar = None):
    # need to access both somevars ???
    # ... if somevar was specified print it or use the global value
    pass

if __name__ == '__main__':
    somevar = "b" # this is just for fun here
    myfunc("c")
    myfunc() # should print "a" (the value of global variable)

使用相同名称至少有两个原因:教育(学习如何使用本地/全局)和模块中的使用。

假设此代码是您的模块的一部分: mymodule 并且您想要执行以下操作:

import mymodule

mymodule.samevar = "default"
...
mymodule.myfunc(somevar = "a")
...
mymodule.myfunc()

正如您可以想象的那样,在这个示例中进行了简化,假设 somevar 参数是一个许多可选参数,并且 myfunc 在许多地方被调用。

Example code from a module:

somevar = "a"

def myfunc(somevar = None):
    # need to access both somevars ???
    # ... if somevar was specified print it or use the global value
    pass

if __name__ == '__main__':
    somevar = "b" # this is just for fun here
    myfunc("c")
    myfunc() # should print "a" (the value of global variable)

There are at least two reasons for using the same name:educational (to learn how to use local/globals) and usage in modules.

Let say that this code is part of your module: mymodule and you want to do things like:

import mymodule

mymodule.samevar = "default"
...
mymodule.myfunc(somevar = "a")
...
mymodule.myfunc()

As you can imagine in this example is simplified, imagine that somevar parameter is one of many optional parameters and that myfunc is called in many places.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

沧笙踏歌 2024-09-20 08:40:36

正如其他答案所说,到目前为止,最好的方法是避免这种非常非常糟糕的设计:只是不要对两个不同的事物使用相同的名称!

如果你被困在这个可怕的设计中,也许是因为你公司的最高架构师颁布了它,并且它是不可协商的(例如,有大量的客户代码依赖于全局和参数的名称),这是首要任务对你来说,就是确保你的简历是最新的,用最好的打印机打印出来,并开始与你的社交网络中的成员取得联系,在一个运作更明智的地方寻找工作;接下来,为了避免在找到更好的工作之前失去健康保险,请尝试

def myfunc(somevar = None):
    if somevar is None:
        print globals().get('somevar')
    else:
        print somevar

将您的 mufunc 重命名为 myfunc,因为这就是它的名称 em> 与(尽管考虑到您假想的最高架构师似乎能够实施极其糟糕的设计,也许他指定该函数应使用与其定义的名称不同的名称来调用?似乎与系统名称冲突一起,这个假设的但已经相当可恨的家伙被认为强加给你了!-)。

By far the best approach, as the other answers say, is to avoid this very, very bad design: just don't use the same names for two different things!

If you're locked into this terrible design, maybe because your company's Supreme Architect decreed it and it's just non-negotiable (e.g., there's tons of customer code relying on the names of both the global and the parameter), the first order of business for you is to make sure your resume is up to date, print it on the best printer, and start getting in touch with members of your social network to look for a job at a place that's run more sensibly; next, to avoid losing health insurance until a better job is found, try

def myfunc(somevar = None):
    if somevar is None:
        print globals().get('somevar')
    else:
        print somevar

I've also renamed your mufunc to myfunc because that's the name it's being called with (though given the incredibly bad design your hypothetical Supreme Architect seems to be able to perpetrate, maybe he's also specified that the function be called by a different name from the one it's defined with? seems to go with the systematic name conflict this hypothetical but already pretty hateful guy is assumed to have foisted on you!-).

顾挽 2024-09-20 08:40:36

为什么局部变量必须与全局变量同名?重命名其中一个似乎是一个简单的解决方案。另一种选择是将全局变量作为参数传递,但这仍然只会为您提供不同的变量名称来访问保存值。

Why does you local variable have to have the same name as the global variable? Renaming one of them seems like a simple solution. Another option is to pass the global variable in as a parameter, but this will still just give you a different variable name to access the save value.

眼眸里的快感 2024-09-20 08:40:36

两种解决方案:

  1. 重命名变量,即重命名为 somevar_
  2. 将全局移动到不同的模块。您可以编写一个模块 myappdefaults

    导入 myappdefaults
    打印 myappdefaults.somevar
    

Two solutions:

  1. Rename the variable, ie to somevar_.
  2. Move the global to a different module. You can write a module myappdefaults

    import myappdefaults
    print myappdefaults.somevar
    
顾忌 2024-09-20 08:40:36

这才是正确的做事方式。

somevar = "a"

def mufunc(_somevar = None):
    global somevar
    if _somevar:
        print _somevar
    else:
        print somevar

if __name__ == '__main__':
    global somevar
    somevar = "b"
    myfunc("c")
    myfunc() $ should print "c"

This is the correct way to do things.

somevar = "a"

def mufunc(_somevar = None):
    global somevar
    if _somevar:
        print _somevar
    else:
        print somevar

if __name__ == '__main__':
    global somevar
    somevar = "b"
    myfunc("c")
    myfunc() $ should print "c"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文