When I define a new-style class in Python, I can get the defined attributes (names and values) by using the __dict__-Attribute, that contains a dictionary of the things.
I’d like to use slots in my classes and their subclasses, because I will created hundreds of thousands of instances and want to save some memory. However, classes that do use __slots__ will not have a __dict__-Attribute so I can not reflectively access their values that way.
Is there another way, preferable one that preserves the order of the attributes defined for such a class?
Any help would be greatly appreciated!
You should use the
dir()built-in function to list members of objects instead accessing of either__dict__or__slots__directly.An instance
__dict__will only list attributes set directly on the instance, whiledir()will list attributes (including methods) on the class and bases of that class as well. It’ll also list anything defined as a slot.You can use the
inspectmodule to help you filter the output ofdir(); if you are not interested in methods for example theinspect.ismethod()can help.