Python 中的条件编译 [英] Conditional compilation in Python
问题描述
如何在 Python 中进行条件编译?
How to do conditional compilation in Python ?
是否使用 DEF ?
推荐答案
Python 与 C 或 C++ 甚至 Java 的编译意义不同,python 文件是动态"编译的,您可以将其视为类似于 Basic 或 Perl 等解释型语言.1
Python isn't compiled in the same sense as C or C++ or even Java, python files are compiled "on the fly", you can think of it as being similar to a interpreted language like Basic or Perl.1
您可以通过仅使用 if 语句来执行与条件编译等效的操作.例如:
You can do something equivalent to conditional compile by just using an if statement. For example:
if FLAG:
def f():
print "Flag is set"
else:
def f():
print "Flag is not set"
您可以对创建类、变量设置和几乎所有内容执行相同操作.
You can do the same for the creation classes, setting of variables and pretty much everything.
模仿 IFDEF 的最接近方法是使用 hasattr 函数.例如:
The closest way to mimic IFDEF would be to use the hasattr function. E.g.:
if hasattr(aModule, 'FLAG'):
# do stuff if FLAG is defined in the current module.
您也可以使用 try/except 子句来捕获名称错误,但惯用的方法是在脚本顶部将变量设置为 None.
You could also use a try/except clause to catch name errors, but the idiomatic way would be to set a variable to None at the top of your script.
- Python 代码被字节编译成 Java 等中间形式,但通常没有单独的编译步骤.以 .py 结尾的原始"源文件是可执行的.
这篇关于Python 中的条件编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!