Junior — Middle
How can you sort a list of attributes within a class in Python?
sobes.tech AI
Answer from AI
In Python, class attributes are usually stored in the __dict__ dictionary. To get and sort a list of class attributes, you can use the sorted() function on the keys of this dictionary. For example:
class MyClass:
z = 3
a = 1
m = 2
# Get a sorted list of class attributes
sorted_attrs = sorted(MyClass.__dict__.keys())
print(sorted_attrs)
This will output a sorted list of attribute names, including methods and special attributes. If you want to get only user-defined attributes, you can filter out the special ones (starting with __).
If you're referring to instance attributes, you can sort self.__dict__ inside class methods.