gpt4 book ai didi

python - 获取类中的属性列表

转载 作者:太空狗 更新时间:2023-10-29 21:16:03 24 4
gpt4 key购买 nike

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

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

我已经做到了,它似乎打印了 key ,但是,它还打印了额外的东西,比如:

['__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']

是否有另一种方法可以做到这一点,所以它只获取键/值。

最佳答案

使用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 ]

关于python - 获取类中的属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19620631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com