如何在Python中从类的属性名称中获取值?

问题描述 投票:0回答:1

我想从类的属性中获取所有值,因此如果我的程序出现错误,我可以查看 json 文件并查看类中的值,然后查看问题。

class Example:
     def __init__(self, x, y):
          self.x = x
          self.y = y

e = Example(1, 2)

data = []
for attribute_name in dir(e):
    attribute = getattr(b, attribute_name)
    if not callable(attribute):
        data.append({"name":attribute_name, "value":attribute.value})

print(data)

我想要什么:

[{"name":"x", "value":1}, {"name":"y", "value":2}]
python-3.x attributes
1个回答
3
投票

你有3个错误。

  1. 正如 Pranav Hosangadi 指出的那样,你的

    getattr(b, attribute_name)
    有一个拼写错误。应该是
    getattr(e, attribute_name)

  2. 您不必要地拨打

    attribute.value
    。只需
    attribute
    就足够了。

  3. 仅使用

    if not callable(attribute)
    将输出
    [{'name': '__module__', 'value': '__main__'}, {'value': 1, 'name': 'x'}, {'name': 'y', 'value': 2}]
    __module__
    不是您想要的,因此请另外检查属性名称中的
    __

话虽如此,下面是完整的更正代码:

class Example:
     def __init__(self, x, y):
        self.x = x
        self.y = y

e = Example(1, 2)

data = []
for attribute_name in dir(e):
    attribute = getattr(e, attribute_name)
    if "__" not in attribute_name and not callable(attribute):
        data.append({"name": attribute_name, "value": attribute})

print(data)
# Prints [{'name': 'x', 'value': 1}, {'name': 'y', 'value': 2}]
© www.soinside.com 2019 - 2024. All rights reserved.