简体   繁体   中英

How to get the names of attributes when classes in Python use __slots__?

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, while dir() 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 inspect module to help you filter the output of dir() ; if you are not interested in methods for example the inspect.ismethod() can help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM