Python listing object attributes

How to get all object attributes in Python

In this tutorial, we will see how to get all object attributes in Python.

Object Attributes in Python

Finding the attributes of an object returns a list of strings containing all of the object’s attributes.
One might even question what are object attributes?

Object attributes are the characteristics of an object. For instance, if an object is a car its attributes are color, price, speed, and many more.
However, in programming object attributes are also the same.
As there may be a lot of attributes for one object, to get the all attributes we use two approaches.
1) dir() function:
dir() function is an inbuilt function that will return a list of attributes and methods of any object.

2) vars() function:
vars() is an inbuilt function that will show all the attributes of a Python object. It takes one parameter, which is also optional. vars function takes an object as a parameter which can be an object, class having __dict__ attribute. If the object doesn’t match the attribute, a TypeError exception is raised.
vars function can be used when we require the attributes as well as the values.

def __init__(self, version, year): self.version = version self.year = year def usedpython(self, year): self.year += year p=Python(version=3, year=2018) print(vars(p))

We can see here that it returns a dictionary of the instance attributes of our object “p”

Читайте также:  Get function result php

It works similarly to the __dict__ attribute, which returns a dictionary of all the instance attributes.

Explanation:
In this post, we learned how to print attributes of a python object with the help of two built-in functions which are dir() and vars().

Источник

Python listing object attributes

Last updated: Feb 22, 2023
Reading time · 3 min

banner

# 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))

get all attributes of an object

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))

pretty print object attributes using pprint

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]

get object properties and values using dict

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

format object attributes into string

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]

get object attributes using vars

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.

Источник

How to Get a List of Class Attributes in Python

To get a list of class attributes in Python, you can use the built-in “dir()” function or the “vars()” function.

A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together.

Using the “dir()” method

class MyClass: attribute1 = "Attribute 1" attribute2 = "Attribute 2" def method1(self): pass # Create an instance of MyClass obj = MyClass() # Get a list of all attributes and methods of obj print(dir(obj))
['__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__', 'attribute1', 'attribute2', 'method1'] 

Using the vars() function

The vars() function returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

class MyClass: attribute1 = "Attribute 1" attribute2 = "Attribute 2" def method1(self): pass # Create an instance of MyClass obj = MyClass() # Get a dictionary of all attributes of obj print(vars(obj)) 

Using getmembers() Method

The getmembers() function from the inspect module in Python is used to get the members of an object, such as a class or module. This function returns a list of tuples, where each tuple contains the name and value of a member.

import inspect class MyClass: attribute1 = "Attribute 1" attribute2 = "Attribute 2" def method1(self): pass # Get the members of MyClass members = inspect.getmembers(MyClass) # Print the members for name, value in members: print(f": ")
__class__: __delattr__: __dict__: , '__dict__': , '__weakref__': , '__doc__': None> __dir__: __doc__: None __eq__: __format__: __ge__:

Using __dict__() Magic Method

The __dict__ is a special attribute in Python that holds the namespace of the object, module, or class. This dictionary object contains all the variables (and their values) that have been defined in the object.

class MyClass: attribute1 = "Attribute 1" attribute2 = "Attribute 2" def method1(self): pass # Create an instance of MyClass obj = MyClass() # Get the __dict__ of obj print(obj.__dict__) 

Источник

Оцените статью