Python:使只读属性可通过 **vars(some_class) 访问

标签 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)))

问题:

有没有一种方法可以通过 **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/

相关文章:

Java 属性文件验证

python - 如何在Python中为一个键存储多个值

Python urllib.request 和 utf8 解码问题

python - 字典的平方值

Python - 从字典中分配和更改列表

ios - 在 ARC 中强 vs 保留

java - 应用程序属性作为静态变量或带有单例的实例变量

Python http.client json 请求和响应。如何?

python - 为什么经过多次在线训练后识别率会下降?

python - 从文件中读取以获取并打印 JSON 数据