【问题标题】:Get list of attributes in class获取类中的属性列表
【发布时间】:2013-11-06 09:20:26
【问题描述】:

如何获得类中的属性列表?例如:

class Test:
    def __init__(self,**kw):
        for k,v in kw.items():
            setattr(self,k,v)
x = Test(value="hello",valueTwo="world")
print(dir(x))

我已经这样做了,它似乎打印了密钥,但它也打印了额外的东西,例如:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__','value','valueTwo']

还有其他方法可以做到这一点,所以它只是获取键/值。

【问题讨论】:

标签: python


【解决方案1】:

使用x.__dict__:

>>> x.__dict__
{'value': 'hello', 'valueTwo': 'world'}

>>> [ v for k,v in x.__dict__.items() if '__' not in k and 'object at' not in k ]

【讨论】:

  • 谢谢我使用 x.__dict__.keys() 来获取密钥,感谢这个我不知道我能做到的方法。
  • 我认为__dict__ 的结果中还会有其他__abc__ 键。为您的答案添加了一些过滤器。
猜你喜欢
  • 2021-03-26
  • 2020-02-29
  • 1970-01-01
  • 2010-10-18
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
相关资源
最近更新 更多