- Python object field list
- # Table of Contents
- # Get all attributes of an Object in Python
- # Pretty print the object’s attributes using pprint()
- # Get each attribute and its value
- # Get an object’s properties and values using __dict__
- # Format the object’s attributes into a string
- # Get an object’s attributes using vars()
- # Additional Resources
- Get a List of Class Attributes in Python
- Using the dir() method to find all the class attributes
- By using __dict__ get class attributes
- By using the inspect module’s getmembers()
- Using the vars() method
Python object field list
Last updated: Feb 22, 2023
Reading time · 3 min
# Table of Contents
# Get all attributes of an Object in Python
Use the dir() function to get all attributes of an object, e.g. print(dir(object)) .
The dir function will return a list of the valid attributes of the provided object.
Copied!class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # 👇️ print(bobby.__dict__) # ------------------------------- attributes = list(bobby.__dict__.keys()) print(attributes) # 👉️ ['first', 'last', 'age'] # ------------------------------- # ['__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__', 'age', 'first', 'last'] print(dir(bobby))
The dir function takes an object and returns a list containing the object’s attributes.
If you pass a class to the function, it returns a list of the names of the class’s attributes, and recursively of the attribute of its base classes.
# Pretty print the object’s attributes using pprint()
If you need to pretty print the attributes of the object, use the pprint() method.
Copied!from pprint import pprint class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # ['__class__', # '__delattr__', # '__dict__', # '__dir__', # '__doc__', # . # ] pprint(dir(bobby))
The pprint.pprint method prints the formatted representation of an object.
# Get each attribute and its value
If you need to get each attribute and its value, use the getattr() function.
Copied!class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) for attribute in dir(bobby): print(attribute, getattr(bobby, attribute))
The getattr function returns the value of the provided attribute of the object.
The function takes the object, the name of the attribute and a default value for when the attribute doesn’t exist on the object as parameters.
# Get an object’s properties and values using __dict__
If you need to get an object’s properties and values, use the __dict__ attribute.
Copied!class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # 👇️ print(bobby.__dict__) # ------------------------------- attributes = list(bobby.__dict__.keys()) print(attributes) # 👉️ ['first', 'last', 'age'] # ------------------------------- values = list(bobby.__dict__.values()) print(values) # 👉️ ['bobby', 'hadz', 30]
You can use the dict.keys() and dict.values() methods if you only need the object’s attribute or values.
# Format the object’s attributes into a string
If you need to format the object’s attributes into a string, use the str.join() method and a formatted string literal.
Copied!class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # 👇️ dict_items([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(bobby.__dict__.items()) result = ', '.join(f'key>=str(value)>' for key, value in bobby.__dict__.items()) print(result) # 👉️ first=bobby, last=hadz, age=30
The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
The string the method is called on is used as the separator between the elements.
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Copied!var1 = 'bobby' var2 = 'hadz' result = f'var1>var2>' print(result) # 👉️ bobbyhadz
Make sure to wrap expressions in curly braces — .
# Get an object’s attributes using vars()
Alternatively, you can use vars() .
The vars() function returns a dictionary containing the object’s properties and values.
Copied!class Employee(): def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # 👇️ print(vars(bob)) only_attributes = list(vars(bob).keys()) print(only_attributes) # 👉️ ['id', 'name', 'salary'] only_values = list(vars(bob).values()) print(only_values) # 👉️ [1, 'bobbyhadz', 100]
The vars function takes an object and returns the __dict__ attribute of the given module, class, instance or any other object that has a __dict__ attribute.
The vars() function raises a TypeError if the provided object doesn’t have a __dict__ attribute.
Which approach you pick is a matter of personal preference. I’d use the __dict__ attribute directly to be more explicit.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
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)
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']
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.
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__)
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 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__', ), ('__delattr__', ), ('__dict__', ), ('__dir__', ), ('__doc__', None), ('__eq__', ), ('__format__', ), ('__ge__', ), ('__getattribute__', ), ('__gt__', ), ('__hash__', ), ('__init__', >), ('__init_subclass__', ), ('__le__', ), ('__lt__', ), ('__module__', '__main__'), ('__ne__', ), ('__new__', ), ('__reduce__', ), ('__reduce_ex__', ), ('__repr__', ), ('__setattr__', ), ('__sizeof__', ), ('__str__', ), ('__subclasshook__', ), ('__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)
Using the vars() method
It takes an object as a parameter and returns its attributes.
import inspect class fruit(): def __init__(self,fruitname,color): self.name=fruitname self.color=color apple=fruit("apple","red") print(vars(apple))
However, you must observe that the above two methods return the class attributes only for the respective base class.