首页 > 解决方案 > python - 如果条件值,预处理器函数打印错误

问题描述

如果我用 C 中的预处理器定义一个函数,然后在 if 中调用它,即使 if 应该为假,它也会运行。

#define HELLO \
{ \
    print("hello world") \
}

i = 1
if i == 2:
    HELLO

这个打印你好。

如果我做这样的普通功能

def hello():
    print("hello world")

i = 1
if i == 2:
    hello()

然后它不会那样做。

请问为什么有区别?我知道括号是不同的,但我尝试了带括号和不带括号的两个,它没有任何区别。

标签: pythonpython-3.xif-statementpreprocessor-directive

解决方案


Python 没有内置的预处理器。宏定义没有达到您的预期:

#define HELLO \
{ \
    print("hello world") \
}

第一行以 开头#,因此 Python 将其视为注释。该行以 continuation 结束\,但注释仍然在第一行之后结束。整个事情相当于:

{print("hello world")}

这会调用print,它会打印hello world,然后使用结果创建 a set,即None

如果要使用 C 预处理器,则需要在将结果传递给 Python 之前显式调用它。


推荐阅读