我来自 PHP 背景,想知道是否有办法在 Python 中做到这一点。
在 PHP 中,你可以像这样用一 block 石头杀死 2 只鸟:
代替:
if(getData()){
$data = getData();
echo $data;
}
我可以这样做:
if($data = getData()){
echo $data;
}
您检查 getData()
是否存在,如果存在,则在一个语句中将其分配给一个变量。
我想知道是否有办法在 Python 中做到这一点?所以不要这样做:
if request.GET.get('q'):
q = request.GET.get('q')
print q
避免两次写request.GET.get('q')
。
最佳答案
见我 8 年的食谱 here只为这个任务。
# In Python, you can't code "if x=foo():" -- assignment is a statement, thus
# you can't fit it into an expression, as needed for conditions of if and
# while statements, &c. No problem, if you just structure your code around
# this. But sometimes you're transliterating C, or Perl, or ..., and you'd
# like your transliteration to be structurally close to the original.
#
# No problem, again! One tiny, simple utility class makes it easy...:
class DataHolder:
def __init__(self, value=None): self.value = value
def set(self, value): self.value = value; return value
def get(self): return self.value
# optional but handy, if you use this a lot, either or both of:
setattr(__builtins__,'DataHolder',DataHolder)
setattr(__builtins__,'data',DataHolder())
# and now, assign-and-set to your heart's content: rather than Pythonic
while 1:
line = file.readline()
if not line: break
process(line)
# or better in modern Python, but quite far from C-like idioms:
for line in file.xreadlines():
process(line)
# you CAN have your C-like code-structure intact in transliteration:
while data.set(file.readline()):
process(data.get())
关于python - 如何避免两次写入 request.GET.get() 以打印它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1663995/