Reputation: 139
I'm trying to get all the members of a class, but in order... Here's a 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']
For the life of me, I can't figure out why its alphabetizing things. Ideally, I want it as ['c','z','a','b']
Upvotes: 2
Views: 1353
Reputation: 4680
You could use the __dict__
attribute:
>>> 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']
Upvotes: 3