【问题标题】:What is this doing (Python)这是在做什么(Python)
【发布时间】:2011-05-04 19:22:54
【问题描述】:

我今天遇到了一段代码,看起来像这样:

class ClassName(object):
     def __init__(self):
         self._vocabulary = None

     def vocabulary(self):
         self._vocabulary = self._vocabulary or self.keys()
         return self._vocabulary

self._vocabulary = self._vocabulary or self.keys() 行到底在做什么?

【问题讨论】:

  • 你的代码 sn-p 的第一部分是无效的 Python 语法。
  • 不完全;我已经为你更正了类声明。

标签: python


【解决方案1】:

这样的一行:

self._vocabulary = self._vocabulary or self.keys()

就是所谓的惰性初始化,当你第一次检索它初始化的值时。所以如果它从未被初始化self._vocabulary 将是None(因为__init__ 方法已经设置了这个值)导致or 的第二个元素的评估所以self.keys() 将被执行,分配返回值到self._vocabulary,从而为以后的请求初始化它。

当第二次调用 vocabulary 时,self._vocabulary 将不会是 None,它将保持该值。

【讨论】:

  • 赞成,但最好澄清一下 __init__ 中的显式行将 self._vocabulary 设置为 None,它不会自动发生。
  • @ncoghlan 感谢您的投票和建议。我编辑了帖子,现在清楚了吗?
【解决方案2】:

简而言之,如果 self._vocabulary 评估为逻辑错误(例如,如果它是 None0False 等),那么它将被替换为 self.keys()

在这种情况下,or 运算符会返回计算结果为逻辑真的任何值。

另外,您的代码应该看起来更像这样:

class Example(object):
     def __init__(self):
         self._vocabulary = None

     def vocabulary(self):
         self._vocabulary = self._vocabulary or self.keys()
         return self._vocabulary

     def keys(self):
         return ['a', 'b']

ex = Example()
print ex.vocabulary()
ex._vocabulary = 'Hi there'
print ex.vocabulary()

【讨论】:

  • The or operator in this case, returns whichever value evaluates to a logical true. - 这有点误导。如果self._vocabulary 的计算结果为False,则self.keys() 被执行并用于赋值,无论其计算结果为True 还是False。请参阅 stackoverflow.com/questions/1452489/… 了解布尔表达式中事物如何计算的说明。
  • @dave - 不,许多其他语言都有类似的运算符。例如,|| 运算符在 ruby​​ 中做同样的事情。等价于 ruby​​ 中的 vocabulary ||= keys()vocabulary = (vocabulary || keys())。除了 ruby​​ 和 python 之外,许多其他语言也很常见。
  • @MattH - 我的措辞稍差,但正是我在说什么。 IE。逻辑测试,而不是身份测试是否is False。 (因此小写的“逻辑错误”而不是对象False)编辑:哎呀,我误读了你的评论。好点...
【解决方案3】:

很难说,代码不会运行的原因有很多。不过猜测一下,我想说它看起来会被评估为逻辑表达式,self._vocabulary 将被 python 评估为False 类型None,而self.keys() 是一种(希望)返回的方法也需要评估的东西。然后这只是两者之间的逻辑或,结果被放入self._vocabulary

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 2011-07-12
    相关资源
    最近更新 更多