基于条件的Python点语法函数

2024-04-23 14:53:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中是否可以基于条件调用点语法函数。简单的例子:

if condition:
  foo().bar().baz()
  lots_of_code()
else:
  foo().baz()
  lots_of_code()

def lots_of_code():
  # lots of code

分为:

foo().(if condition: bar()).baz()
# lots of code only once

Tags: of函数onlyiffoodef语法bar
2条回答

因为foo()在这两种情况下都被调用,所以从无条件调用开始。将该对象保存到f,以便调用f.baz()。不过,在此之前,请检查您的条件,看看f是否真的应该是foo().bar()的结果。你知道吗

f = foo()
if condition:
    f = f.bar()
f.baz()

不,不可能。你知道吗

属性引用的语法是

attributeref ::=  primary "." identifier

引用documentation

An attribute reference is a primary followed by a period and a name

名称必须是a regular Python identifier,标识符不能包含像(这样的特殊字符。你知道吗

但是,您可以使用简单的条件表达式来选择

(foo().bar() if condition else foo()).baz()

相当于

if condition:
    primary = foo().bar()
else:
    primary = foo()

primary.baz()

注意,在这种情况下,我们必须使用括号,因为属性引用比条件表达式有higher precedence。你知道吗

相关问题 更多 >