[英]How to get all members of a class in python in order?
I'm trying to get all the members of a class, but in order... Here's a MWE我正在尝试获取 class 的所有成员,但是按顺序...这是 MWE
class example:
def __init__(self):
self.c = 3
self.z = 5
self.a = 5
self.b = 3
ex = example()
members = [attr for attr in dir(ex) if not \
callable(getattr(ex, attr)) and not attr.startswith("__")]
print(members)
This prints: ['a', 'b', 'c', 'z']
这打印:
['a', 'b', 'c', 'z']
For the life of me, I can't figure out why its alphabetizing things.对于我的生活,我无法弄清楚为什么它会按字母顺序排列。 Ideally, I want it as
['c','z','a','b']
理想情况下,我希望它为
['c','z','a','b']
You could use the __dict__
attribute:您可以使用
__dict__
属性:
>>> class example:
def __init__(self):
self.c = 3
self.z = 5
self.a = 5
self.b = 3
>>> example().__dict__
{'c': 3, 'z': 5, 'a': 5, 'b': 3}
>>> list(example().__dict__)
['c', 'z', 'a', 'b']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.