Here are 4 ways to get a list of class attributes in Python:
- Using dir()
- Using getmembers()
- Using vars()
- Using __dict__()
Method 1: Using dir()
This built-in function provides the most comprehensive list of attributes for any object, including all its class and instance attributes, as well as methods.
Keep in mind that it also lists inherited attributes.
Example
class MyClass:
class_attribute = "I'm a class attribute!"
print(dir(MyClass))
Output
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'class_attribute']
Method 2: Using getmembers()
The getmembers() function from the inspect module can be used to get class attributes and methods.
Example
import inspect
class MyClass:
class_attribute = "I'm a class attribute!"
attributes = [a for a in inspect.getmembers(MyClass) if not callable(a[1]) and not a[0].startswith('__')]
print(attributes)
Output
[('class_attribute', "I'm a class attribute!")]
Method 3: Using vars()
The vars() function, when applied to a class, returns the __dict__ attribute of that class.
This __dict__ attribute is a dictionary containing all the attributes (including methods) that are directly defined for the class, excluding inherited attributes.
However, it’s important to note that not every object has a __dict__ attribute. Therefore, vars() will not work with all types of objects.
Example
class MyClass:
class_attribute1 = "I'm a class attribute!"
class_attribute2 = 17
def my_method(self):
pass
attributes = vars(MyClass)
print(attributes)
Output
{'__module__': '__main__', 'class_attribute1': "I'm a class attribute!", 'class_attribute2': 17, 'my_method': <function MyClass.my_method at 0x10477c7c0>,
'__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}
Method 4: Using __dict__()
The __dict__() gives you a dictionary of attributes and their corresponding values.
However, it only lists attributes that were set in the class body, not methods or inherited attributes.
Example
class MyClass:
class_attribute = "I'm a class attribute!"
print(MyClass.__dict__)
Output