在Python赋值时可以使用or代替if…else…达到简化代码的作用
def assign_with_or(a=None, b=None):
res = a or b
print (res)
if __name__ == '__main__':
assign_with_or(a='a')
assign_with_or(a='a', b='b')
assign_with_or(b='b')
其中assign_with_or()等价于如下函数
def assign_with_or(a=None, b=None):
if a:
res = a
else:
res = b
print (res)
if __name__ == '__main__':
assign_with_or(a='a')
assign_with_or(a='a', b='b')
assign_with_or(b='b')
两个函数输出结果一致
root@root:~/Desktop$ python3 test.py
a
a
b
进一步,and也可以用在赋值语句中
def assign_with_log_opr(a=None, b=None, c=None):
res = a and b or c
print (res)
if __name__ == '__main__':
assign_with_log_opr(a='a', b='b', c='c')
assign_with_log_opr(b='b', c='c')
assign_with_log_opr(a='a', c='c')
assign_with_log_opr(a='a')
上述‘assign_with log_opr()’输出结果为
b
c
c
None
等价于
def func(a=None, b=None, c=None):
if a and b:
res = b
else:
res = c
print (res)
在Django中也用到这种语法,Django初始化项目时调用的模块’Django/core/management/__init__.py’:
class ManagementUtility:
"""
Encapsulate the logic of the django-admin and manage.py utilities.
"""
def __init__(self, argv=None):
self.argv = argv or sys.argv[:]
self.prog_name = os.path.basename(self.argv[0])
...