仅当变量为True时才执行函数

Mar*_*rek 3 python methods idiomatic

我想只在语句为True时才运行函数.例如,我有:

def foo():
    # do something
Run Code Online (Sandbox Code Playgroud)

我只想在这个时候运行它

var == True
Run Code Online (Sandbox Code Playgroud)

而在关键的处理我希望做这样的事情:

if k.key() == Key_UP and var:
    foo()
Run Code Online (Sandbox Code Playgroud)

我从多个地方调用此函数,我不想重复var条件.另外,我想要这样的东西:

def foo():
    if var:
        # do something
Run Code Online (Sandbox Code Playgroud)

我展示的最后一个是最接近我的需求,但我认为它可以通过其他方式完成.Python 3的惯用语.

问候!

PS.我想得到这样的东西:

def foo() if var == True:
    # do something
Run Code Online (Sandbox Code Playgroud)

Ale*_*der 6

像这样?

 def foo():
    print('foo')

>>> bool = True
>>> if bool: foo()
foo

>>> bool = False
>>> if bool: foo()
Run Code Online (Sandbox Code Playgroud)

如果上述情况不合适,我认为您不想清楚自己想要做什么,或者为什么这样的事情不起作用:

def foo():
    if not var:
        return
Run Code Online (Sandbox Code Playgroud)