我想创建一个别名来调用不带括号的函数。类似于:
>ls=os.getcwd()
>ls
>"/path1"
>os.chdir("/path2")
>ls
>"/path1" ( the wanted output would be "/path2" )
事实上,“ls”始终具有相同的值,即分配时的值。
我当然可以:
>ls=os.getcwd
然后用
调用>ls()
但我想要的是不带括号调用函数(当然当函数不需要参数时)
我试过了
>def ListDir():
> print(os.getcwd())
>
>ls=ListDir()
但是不起作用。我怎样才能做这样的事情?这是可能的? (仅当很容易做到时)
最佳答案
Python 更喜欢你明确;如果你想重新计算一个表达式,你必须调用它。但如果你真的希望它在 Python 交互式解释器中工作,你就必须破解它。
您只是回显变量,而不是执行表达式。该变量不会仅仅因为您要求交互式解释器回显它而改变。
也就是说,除非你连接到回显机制。您可以通过覆盖__repr__
method来做到这一点:
class EvaluatingName(object):
def __init__(self, callable):
self._callable = callable
def __call__(self):
return self._callable()
def __repr__(self):
return repr(self())
ls = EvaluatingName(os.getcwd)
演示:
>>> import os
>>> class EvaluatingName(object):
... def __init__(self, callable):
... self._callable = callable
... def __call__(self):
... return self._callable()
... def __repr__(self):
... return repr(self())
...
>>> ls = EvaluatingName(os.getcwd)
>>> os.chdir('/')
>>> ls
'/'
>>> os.chdir('/tmp')
>>> ls
'/private/tmp'
现在可以这样做,因为每次表达式生成 None
以外的值时,都会回显该值,并且回显会在对象上调用 repr()
。
请注意,这在交互式解释器或打印之外不起作用。在其他上下文(例如脚本)中,您可能每次都必须将对象转换为字符串。例如,您不能将其用作需要字符串的函数的参数。
这会起作用:
os.path.join(ls(), 'foo.txt') # produce the value first
但这不会:
os.path.join(ls, 'foo.txt') # throws an AttributeError.
关于python - python中通过变量或不带括号调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35199556/