【问题标题】:Scope of variables in Python methods with identical default parameters?具有相同默认参数的 Python 方法中的变量范围?
【发布时间】:2014-08-11 02:28:35
【问题描述】:

经过一番搜索后,我找不到任何涵盖此内容的示例。但我可能没有使用正确的术语,因为我对这种情况感到困惑,甚至问这是否有意义?所以我觉得这可能是重复的。

但是,如果你有一个 Python 类,其中有两个方法具有同名的参数,那么它的行为是什么?

class Foo():

    def __init__(self, arg1=1, arg2=2):

    def methodOne(self, amount, setting=None, extra=0):         

    def methodTwo(self, amount, setting=None):
        ...
        #What is going on with setting here? What is setting referring to?
        self.methodOne(amount, setting=setting) 

【问题讨论】:

  • @John1024 self 是在我正在查看的代码中定义的,忘了说,我更新了问题。

标签: python variables scope default-parameters default-arguments


【解决方案1】:

左侧的setting只能引用关键字参数,右侧的setting只能引用名称。这就是 Python 解析器的工作原理。

【讨论】:

  • 我忘了在我的问题中添加自我,因为我正在查看的代码已经自我定义,现在它匹配了,所以也许这会改变你的答案?
  • 没有。 Python 解析器不会改变。
  • 啊,好吧,在那种情况下,我还是不明白,哈哈。 “关键字参数”和“名称”是什么意思?
  • 好的,在self.methodOne(amount, setting=setting) 中,第二个参数是关键字参数吗?而您恰好传递了值设置?也可以是self.methodOne(amount, setting='no') 之类的东西?我想我现在明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
  • 2011-07-25
  • 1970-01-01
  • 2016-06-15
  • 1970-01-01
  • 2021-07-12
  • 2015-08-21
相关资源
最近更新 更多