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._vocab开发者_C百科ulary = self._vocabulary or self.keys()
doing?
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.
When a second time vocabulary
is called self._vocabulary
won't be None
and it will keep that value.
In a nutshell, if self._vocabulary
evaluates to a logical false (e.g. if it's None
, 0
, False
, etc), then it will be replaced with self.keys()
.
The or
operator in this case, returns whichever value evaluates to a logical true.
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. Then it's just a logical OR between the two and the result gets put into self._vocabulary
.
精彩评论