将当前上下文传递给str.format?

时间:2014-09-18 07:44:31

标签: python string-formatting

是否可以将当前上下文(例如函数)作为参数传递给format()?

def test(a):
    b = Person('b')
    print "{a.name} joins {b.name}".format(???)

是否有可能捕获当前的函数上下文并将其传递给format(),因为它可以在ruby中使用binding()函数?

1 个答案:

答案 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