python - 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()
然后它不会那样做。
请问为什么有区别?我知道括号是不同的,但我尝试了带括号和不带括号的两个,它没有任何区别。
解决方案
Python 没有内置的预处理器。宏定义没有达到您的预期:
#define HELLO \
{ \
print("hello world") \
}
第一行以 开头#
,因此 Python 将其视为注释。该行以 continuation 结束\
,但注释仍然在第一行之后结束。整个事情相当于:
{print("hello world")}
这会调用print
,它会打印hello world
,然后使用结果创建 a set
,即None
。
如果要使用 C 预处理器,则需要在将结果传递给 Python 之前显式调用它。
推荐阅读
- python - 测试目录中的相对导入
- ruby-on-rails - Rails 应用程序 Stripe 付款在生产中不起作用
- reactjs - React 无法弄清楚为什么我会收到太多重新渲染错误
- scapy - 如何使用 scapy 发送命令?
- apache-kafka - 在 Kafka Streams DSL 中读取已经分区的主题
- node.js - Sequelize 递减 JSON 列
- python - 如何在Python中通过文本获取href链接
- discord - 在 Discord 上发送图像是 Bot
- haskell - Haskell 模式匹配隐式类型
- python - 无法从 vscode 执行 Powershell,因为它以某种方式在 Python 调试模式下运行