由于 Python 的作用域规则,所有在某个作用域内初始化的变量此后都可用。由于条件不会引入新的作用域,因此不一定需要其他语言中的构造(例如在该条件之前初始化变量)。例如,我们可能有:
def foo(optionalvar = None):
# some processing, resulting in...
message = get_message()
if optionalvar is not None:
# some other processing, resulting in...
message = get_other_message()
# ... rest of function that uses message
或者,我们可以改为:
def foo(optionalvar = None):
if optionalvar is None:
# processing, resulting in...
message = get_message()
else:
# other processing, resulting in...
message = get_other_message()
# ... rest of function that uses message
当然,get_message
and get_other_message
函数可能有很多行代码,并且基本上是不相关的(您可以假设每条路径之后程序的状态是相同的);这里的目标是message
准备好在本部分功能之外使用。
我在其他问题中多次看到后一种结构,例如:
- https://stackoverflow.com/a/6402327/18097 https://stackoverflow.com/a/6402327/18097
- https://stackoverflow.com/a/7382688/18097 https://stackoverflow.com/a/7382688/18097
哪种结构更容易被接受?
Python 还有一个非常有用的 if 语法模式,您可以在此处使用
message = get_other_message() if optional_var else get_message()
或者如果你想与 None 严格比较
message = get_other_message() if optional_var is not None else get_message()
与示例 1) 不同,您发布的内容不会不必要地调用 get_message() 。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)