Вопрос

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top