簡體   English   中英

如何按順序獲取 python 中 class 的所有成員?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM