我经常使用成语 '{var_name}'.format(**vars(some_class))
。
但是,当我使用属性时,我无法使用它来获取属性值。
考虑这个程序:
#!/usr/bin/env python
class Foo(object):
def __init__(self):
self._bar = None
self.baz = 'baz here'
@property
def bar(self):
if not self._bar:
# calculate some value...
self._bar = 'bar here'
return self._bar
if __name__ == '__main__':
foo = Foo()
# works:
print('{baz}'.format(**vars(foo)))
# gives: KeyError: 'bar'
print('{bar}'.format(**vars(foo)))
问题:
有没有一种方法可以通过 **vars(some_class)
访问属性值?
最佳答案
简短回答:不,不可能使用 .format(**vars(object))
做你想做的事,因为属性不使用__dict__
和来自 vars
文档:
vars(...)
vars([object])
-> dictionary
- Without arguments, equivalent to
locals()
.- With an argument, equivalent to
object.__dict__
.
但是您可以使用不同的格式说明符实现您想要的,例如属性查找:
In [2]: '{.bar}'.format(Foo())
Out[2]: 'bar here'
请注意,您只需在名称中添加一个前导 .
(点)即可得到您想要的内容。
旁注:您应该使用 format_map
方法,而不是使用 .format(**vars(object))
:
In [6]: '{baz}'.format_map(vars(Foo()))
Out[6]: 'baz here'
使用 dict
参数调用 format_map
等同于使用 **
符号调用 format
,但它效率更高,因为它在调用函数之前不必进行任何类型的解包。
关于Python:使只读属性可通过 **vars(some_class) 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18611759/