pho*_*bos 5 python dictionary properties
我经常使用这个成语'{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)))
Run Code Online (Sandbox Code Playgroud)
题:
有没有办法通过**vars(some_class)?访问属性值?
简短回答:不,不可能用来.format(**vars(object))做你想做的事,因为属性不使用__dict__并且来自vars文档:
vars(...)
vars([object])-> 字典
- 没有参数,相当于
locals().- 带参数,等价于
object.__dict__.
但是,您可以使用不同的格式说明符来实现您想要的,例如属性查找:
In [2]: '{.bar}'.format(Foo())
Out[2]: 'bar here'
Run Code Online (Sandbox Code Playgroud)
请注意,您只需.在名称中添加一个前导(点)即可获得您想要的内容。
旁注:而不是使用.format(**vars(object))你应该使用format_map方法:
In [6]: '{baz}'.format_map(vars(Foo()))
Out[6]: 'baz here'
Run Code Online (Sandbox Code Playgroud)
format_map使用dict参数调用等同于format使用**符号调用,但它更有效,因为它在调用函数之前不必进行任何类型的解包。
| 归档时间: |
|
| 查看次数: |
456 次 |
| 最近记录: |