[英]What is this doing (Python)
I came across a piece of code today that looks like this:我今天遇到了一段代码,如下所示:
class ClassName(object):
def __init__(self):
self._vocabulary = None
def vocabulary(self):
self._vocabulary = self._vocabulary or self.keys()
return self._vocabulary
What exactly is the line self._vocabulary = self._vocabulary or self.keys()
doing? self._vocabulary = self._vocabulary or self.keys()
行到底在做什么?
A line like this:像这样的一行:
self._vocabulary = self._vocabulary or self.keys()
Is what's called lazy initialization, when you are retrieving the value for the first time it initializes.就是所谓的延迟初始化,当您第一次检索它初始化的值时。 So if it has never been initialized
self._vocabulary
will be None
(because the __init__
method had set this value) resulting in the evaluation of the second element of the or
so self.keys()
will be executed, assigning the returning value to self._vocabulary
, thus initializing it for future requests.所以如果它从未被初始化
self._vocabulary
将是None
(因为__init__
方法已经设置了这个值)导致评估的第二个元素or
self.keys()
将被执行,将返回值分配给self._vocabulary
,从而为将来的请求初始化它。
When a second time vocabulary
is called self._vocabulary
won't be None
and it will keep that value.当第二次调用
vocabulary
时self._vocabulary
不会是None
并且它将保持该值。
In a nutshell, if self._vocabulary
evaluates to a logical false (eg if it's None
, 0
, False
, etc), then it will be replaced with self.keys()
.简而言之,如果
self._vocabulary
评估为逻辑假(例如,如果它是None
、 0
、 False
等),那么它将被替换为self.keys()
。
The or
operator in this case, returns whichever value evaluates to a logical true.在这种情况下,
or
运算符返回计算结果为逻辑真的任何值。
Also, your code should look more like this:此外,您的代码应该看起来更像这样:
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()
Hard to say, the code will not run for a number of reasons.很难说,代码不会运行的原因有很多。 To guess though, I'd say it looks like it would be evaluated as a logical expression,
self._vocabulary
would be evaluated False
by python as type None
, and self.keys()
is a method that would (hopefully) return something to be evaluated as well.不过,猜测一下,我会说它看起来会被评估为逻辑表达式,
self._vocabulary
将被 python 评估为False
类型None
,而self.keys()
是一种(希望)返回一些东西的方法也被评估。 Then it's just a logical OR between the two and the result gets put into self._vocabulary
.然后这只是两者之间的逻辑或,结果被放入
self._vocabulary
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.