![](/img/trans.png)
[英]How to list specific attribute of all members in my class (Python 3.5.3)
[英]How to get all members of a class in python in order?
我正在嘗試獲取 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)
這打印: ['a', 'b', 'c', 'z']
對於我的生活,我無法弄清楚為什么它會按字母順序排列。 理想情況下,我希望它為['c','z','a','b']
您可以使用__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.