是否可以将当前上下文(例如函数)作为参数传递给format()?
def test(a):
b = Person('b')
print "{a.name} joins {b.name}".format(???)
是否有可能捕获当前的函数上下文并将其传递给format(),因为它可以在ruby中使用binding()函数?
答案 0 :(得分:3)
您可以使用locals()
result dictionary作为关键字参数:
def test(a):
b = Person('b')
print "{a.name} joins {b.name}".format(**locals())
locals()
构造一个本地名称的字典(在一个方向上,你不能用它来改变本地人)。 call expression中的**expression
语法采用expression
的结果,并将其视为映射使用键值对作为额外的关键字参数。
演示:
>>> class Person(object):
... def __init__(self, name):
... self.name = name
...
>>> def test(a):
... b = Person('b')
... print "{a.name} joins {b.name}".format(**locals())
...
>>> test(Person('a'))
a joins b