Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all fields of a class (and no methods)?

Suppose o is a Python object, and I want all of the fields of o, without any methods or __stuff__. How can this be done?

I've tried things like:

[f for f in dir(o) if not callable(f)]  [f for f in dir(o) if not inspect.ismethod(f)] 

but these return the same as dir(o), presumably because dir gives a list of strings. Also, things like __class__ would be returned here, even if I get this to work.

like image 603
Eric Wilson Avatar asked Feb 21 '14 21:02

Eric Wilson


People also ask

How do you list all methods in a Python class?

To list the methods for this class, one approach is to use the dir() function in Python. The dir() function will return all functions and properties of the class.

What is __ slots __ in Python?

__slots__ is a class variable. If you have more than one instance of your class, any change made to __slots__ will show up in every instance. You cannot access the memory allocated by the __slots__ declaration by using subscription. You will get only what is currently stored in the list.

What is __ dict __ in Python?

The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __dict__.


1 Answers

You can get it via the __dict__ attribute, or the built-in vars function, which is just a shortcut:

>>> class A(object): ...     foobar = 42 ...     def __init__(self): ...         self.foo = 'baz' ...         self.bar = 3 ...     def method(self, arg): ...         return True ... >>> a = A() >>> a.__dict__ {'foo': 'baz', 'bar': 3} >>> vars(a) {'foo': 'baz', 'bar': 3} 

There's only attributes of the object. Methods and class attributes aren't present.

like image 138
Maxime Lorant Avatar answered Sep 20 '22 15:09

Maxime Lorant