[英]Get list of attributes in class
How would I get a list of attributes in a class? 我如何获得课程中的属性列表? For example: 例如:
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))
I've done that and it seems to print the keys but, it also prints extra stuff like: 我已经做到了,它似乎打印键,但它还打印额外的东西,如:
['__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']
is there another way to do this so it just gets the keys/values. 有没有另一种方法来做到这一点,它只是得到键/值。
Use x.__dict__
: 使用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 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.