python - 如何避免两次写入 request.GET.get() 以打印它?

标签 python if-statement dictionary

我来自 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/

相关文章:

python - 尝试在 python 中使用 HTTP POST 请求进行 POST

windows - 如何在批处理文件中正确限制 IF 命令?

python - 如何读取 CSV 文件以仅将最新的三个值放入字典中?

c# - 字典包含键并在一个函数中获取值

javascript - IF 语句的多个 OR 条件

python - 1.10 中关于 django.shortcuts.render() 方法签名的困惑

javascript - Python:有没有办法获取由 Javascript 动态创建的 HTML?

python - 将数据帧作为类方法返回

python - 如何将参数传递给 Django 的 PasswordChangeForm 的 __init__ 函数

java - 我遇到前导零问题