Get a List of Class Attributes in Python
Python classes are mostly templates for creating new objects. The contents/attributes of the objects belonging to a class are described by the class.
What exactly are class attributes?
Class attributes are nothing but variables of a class. It is important to note that these variables are shared between all the instances of the class.
class example: z=5 obj1=example() print(obj1.z) obj2=example() print(obj1.z+obj2.z)
5 10
In the above example code, z is a class attribute and is shared by the class instances obj1 and obj2.
In this tutorial, you will learn how to fetch a list of the class attributes in Python.
Using the dir() method to find all the class attributes
It returns a list of the attributes and methods of the passed object/class. On being called upon class objects, it returns a list of names of all the valid attributes and base attributes too.
Syntax: dir(object) , where object is optional.
Here, you can obtain the list of class attributes;
- By passing the class itself
class example: z=5 obj1=example() print(obj1.z) obj2=example() print(obj1.z+obj2.z) print(dir(example)) #By passing the class itself
5 10 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'z']
- By passing the object of the class
class example: z=5 obj1=example() print(obj1.z) obj2=example() print(obj1.z+obj2.z) print(dir(obj1)) #By passing the object of class
5 10 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'z']
However, the dir() method also returns the magic methods of the class along with the class attributes.
By using __dict__ get class attributes
It stores/returns a dictionary of the attributes that describe an object. Let us understand the same by looking into an example.
Syntax: object.__dict__
class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") print(apple.name) print(apple.color) print(apple.__dict__)
apple red {'name': 'apple', 'color': 'red'}
Here, apple is an object belonging to class fruit. So, the __dict__ has returned a dictionary that contains the attributes of the object i.e., apple.
Also, you can further get just the keys or values for the particular object by using the dictionary’s key, value system of storage.
class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") print(apple.name) print(apple.color) print(apple.__dict__) print(apple.__dict__.keys()) print(apple.__dict__.values())
apple red {'name': 'apple', 'color': 'red'} dict_keys(['name', 'color']) dict_values(['apple', 'red'])
By using the inspect module’s getmembers()
The getmembers() function retrieves the members of an object such as a class in a list.
import inspect class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") print(inspect.getmembers(apple))
[('__class__', <class '__main__.fruit'>), ('__delattr__', <method-wrapper '__delattr__' of fruit object at 0x000002C7B60D0D48>), ('__dict__', {'name': 'apple', 'color': 'red'}), ('__dir__', <built-in method __dir__ of fruit object at 0x000002C7B60D0D48>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of fruit object at 0x000002C7B60D0D48>), ('__format__', <built-in method __format__ of fruit object at 0x000002C7B60D0D48>), ('__ge__', <method-wrapper '__ge__' of fruit object at 0x000002C7B60D0D48>), ('__getattribute__', <method-wrapper '__getattribute__' of fruit object at 0x000002C7B60D0D48>), ('__gt__', <method-wrapper '__gt__' of fruit object at 0x000002C7B60D0D48>), ('__hash__', <method-wrapper '__hash__' of fruit object at 0x000002C7B60D0D48>), ('__init__', <bound method fruit.__init__ of <__main__.fruit object at 0x000002C7B60D0D48>>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x000002C7B5790548>), ('__le__', <method-wrapper '__le__' of fruit object at 0x000002C7B60D0D48>), ('__lt__', <method-wrapper '__lt__' of fruit object at 0x000002C7B60D0D48>), ('__module__', '__main__'), ('__ne__', <method-wrapper '__ne__' of fruit object at 0x000002C7B60D0D48>), ('__new__', <built-in method __new__ of type object at 0x00007FFC234B7B30>), ('__reduce__', <built-in method __reduce__ of fruit object at 0x000002C7B60D0D48>), ('__reduce_ex__', <built-in method __reduce_ex__ of fruit object at 0x000002C7B60D0D48>), ('__repr__', <method-wrapper '__repr__' of fruit object at 0x000002C7B60D0D48>), ('__setattr__', <method-wrapper '__setattr__' of fruit object at 0x000002C7B60D0D48>), ('__sizeof__', <built-in method __sizeof__ of fruit object at 0x000002C7B60D0D48>), ('__str__', <method-wrapper '__str__' of fruit object at 0x000002C7B60D0D48>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x000002C7B5790548>), ('__weakref__', None), ('color', 'red'), ('name', 'apple')]
To get a list of just the passed object’s attribute, i.e., to remove all the public and private in-built attributes/magic methods from the list;
import inspect class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") for i in inspect.getmembers(apple): if not i[0].startswith('_'): if not inspect.ismethod(i[1]): print(i)
('color', 'red') ('name', 'apple')
Using the vars() method
It takes an object as a parameter and returns its attributes.
Syntax: vars(object)
import inspect class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") print(vars(apple))
{'name': 'apple', 'color': 'red'}
However, you must observe that the above two methods return the class attributes only for the respective base class.
For a better understanding do read, An introduction to classes and objects in Python
Leave a Reply