How to Print Object Attributes in Python? (with Code)
Python is an object-oriented programming language. In fact, everything in Python is an object (even a class)! Every object has some attributes associated with them. Now, to work well with any object you must know about its attributes.
Hence in this article, we’ll discuss objects, attributes, and ways to print these objects’ attributes in Python. So, let’s get started.
What is an Object in Python?
An object is an instance of a class. It is often regarded as a real-world entity. An object may constitute properties, data (or), and a few methods to operate on that data. It is needed to instantiate a class. Each object has a unique identity.
For instance, consider the human race as a class. So each human will have a name, age, weight, height, and many other properties. Each person can be uniquely identified as an object, (including me, you, your friend, or any other human you know!)
Let’s take an example of how to declare an object in Python:
Note that the name and age variables are attributes of the objects of class ‘human’.
Output:
The above example displays how an object is created (for a user-defined class) and accessed in Python. We have also declared attributes of the object (here, human1 & human2) and accessed them.
Now, we should take a better look at the attributes of an object.
What is an Attribute in Python?
An attribute can be defined as a property of a class or an object. These are data members inside a class (or object) that represents their features. These attributes can be properties (state or value) defining an object or any method acting upon that object.
For instance, let’s take our previous example: class human. The name and age variables declared in the class human are actually ‘attributes’ of ‘human’. Along with them, actions (functions) like running, sleeping, reading, walking, and swimming are also attributes of ‘human’.
You might get confused between an attribute and an object. The difference between an object and an attribute is that An object is a real-world entity while an attribute is a characteristic of that object.
These attributes are generally defined within a class and shared among all the instances (objects) of that class. An object can be accessed using these attributes.
Attributes are also classified into two types:
- Class Attributes
- Instance (object) Attributes
An Instance attribute is a data member of an object. It is associated with the properties of an object. So, every instance of that class will have the same instance attributes. (It is the purpose of a class, after all!). Their scope of access also lies within the object creation.
For instance, refer to the variables ‘name’ and ‘age’ of class ‘human’. These are instance variables, allocated to every object separately.
Class Attributes is a data member of the whole class. These attributes share the same memory space and are accessed by all the objects in common.
To learn more about attributes, check our article on static variables in python.
Now that we have learned about objects and attributes, we’re all set to learn how to print all attributes of an object in Python.
4 Ways to Print all Attributes of an Object in Python
In order to code efficiently and access an object to obtain its full functionality, one must be aware of all the attributes of the object. Thus, given below are different ways to print all attributes of an object in Python.
01) Using __dir__() method
Python offers an in-built method to print out all attributes of an object (Now, this object may be anything in Python). This method is also known as a magic method or a dunder method in Python.
Syntax:
print(objectName.__dir__())
Let’s jump on to an example for better understanding:
Output:
Note that the method returns a list with the user-defined attributes given priority.
You’ll be surprised to know that, the __dir__() method can also be modified. You can define the __dir__() method in a class to override the default __dir__() method. Let’s modify the __dir__() method for the above example:
Output:
The s.__dir__() statement calls for the user-defined method which overrides the default dunder method. Notice how different the outputs of the default __dir__() method and the user-defined __dir__() method are.
02) Using dir()
Python offers an in-built function to list out all the attributes of an object. This function returns all attributes (variables, methods, or objects) associated with the passed parameter, in a given scope.
Syntax:
print(dir(parameter))
Passing the parameter is optional. If you don’t pass a parameter, the dir() function will return all the attributes in the local scope.
Let’s take an example:
Output:
See! The dir() function returned all the in-built and user-defined attributes in the local scope.
Although the above example had a small list, sometimes the output is long enough to have low readability. To deal with this, Python offers a pprint module.
The «pprint module» is used to print the list in a well-formatted way. Take a look at the example below.
Example: To print the attributes of objects in Python by using the dir() function with an object as an argument.
Output:
The pprint() method relates directly to «pretty print»! Take note of how each feature is printed on a separate line. This improves the output’s readability.
Now that we’ve seen some dir() examples, let’s go over some key points about the dir() function:
- It returns a list of all the characteristics of an object in the local scope.
- It internally invokes the __dir__() function. Internally, the dir() function implements its functionality via the __dir__() method.
- The dir() function provides an alphabetically sorted output.
Before moving to the next method, let’s compare the dir() and __dir__() methods.
Working with dir() function and __dir__() method
a. You already know that the dir() function internally calls for __dir__() method for implementation. Hence, defining the __dir__() method will also change the functionality (and hence output) of the dir() function. Let’s take the above example and call the dir() method:
Output:
Notice the difference between the outputs returned by dir() function and the __dir__() method. While the __dir__() method provides the defined list as-it-is, the dir() function produces a sorted list of attributes.
b. Now let’s take another example of modifying the __dir__() method. You’ll be surprised by the output:
Output:
The __dir__() method works fine but the dir() function produces a TypeError. You must be wondering WHY!
The code did work for the previous example, didn’t it? So why the error? Because the dir() method compares the attributes to produce a sorted list as output. Hence, since the types, string («alice») and integer (1,2 and rest), cannot be compared with each other, therefore calling dir() method on this produces an error.
Note: The dir() function, in absence of the __dir__() method, calls for the __dict__ attribute to return a list of all the attributes of an object in Python.
03) Using vars() function
Python offers the vars() function which returns a ‘dictionary’ of all the instance attributes along with their values. It is similar to the above methods, the only difference being, vars() focuses only on instance attributes and also returns their values along with them.
print(vars(objectName))
Passing any parameter to the vars() function is optional. It can also be called without passing any parameter to it.
Let’s take a few examples to understand the different cases:
a. Without passing any parameter
Output:
Note how each attribute is followed by its value.
b. Passing parameter to the vars() function
Output:
When the object (here s) is passed as an argument to the vars() method, it produces a dictionary of only the attributes associated with the instance, leaving out the rest of the attributes (as obtained in the above example).
Also, note that the vars() function internally calls for the __dict__ attribute for implementation. The __dict__ attribute is simply a dictionary containing all attributes of that object.
Let’s look at the output when we use the __dict__ attribute in the above example:
Output:
The output is same! (Hence, remember that the vars() function will produce an error when passed over an object which does not have the __dir__ attribute.)
04) Using inspect module
The inspect module in Python helps in inspecting certain modules or objects that are included in the code. It includes several useful functions that provide information about live objects (like class, function, object, and methods). It can be used to obtain an analysis of objects, for example, to examine a class’s content or to display information about an object.
To print all the attributes of an object in Python, you can use the ‘getmembers()‘ function of the inspect module. This function returns the list of tuples containing the attributes along with their values.
Refer to the below image for better readability of the output:
Let’s take an example for a better understanding:
I’ve used pprint module to increase the readability of the output.
Output:
Note that this list contains tuples in sorted order. So, the getmembers() function returns a sorted list of all the attributes of an object in Python, along with their respective values.
Conclusion
So far we’ve discussed different ways to print all attributes of an object in Python. But before moving on to list out all the attributes, you must be able to differentiate between instance attributes and class attributes. So, try and test out these methods along with their variations to understand them better.
List attributes of an object [duplicate]
Is there a way to grab a list of attributes that exist on instances of a class?
The desired result is that «multi, str» will be output. I want this to see the current attributes from various parts of a script.
18 Answers 18
You may also find pprint helpful.
Then you can test what type is with type() or if is a method with callable() .
All previous answers are correct, you have three options for what you are asking
vars(obj) returns the attributes of an object.
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.
Using getmembers() you can see all attributes of your class, along with their value. To exclude private or protected attributes use .startswith(‘_’) . To exclude methods or functions use inspect.ismethod() or inspect.isfunction() .
Note that ismethod() is used on the second element of i since the first is simply a string (its name).
Offtopic: Use CamelCase for class names.
This of course will print any methods or attributes in the class definition. You can exclude «private» methods by changing i.startwith(‘__’) to i.startwith(‘_’)
You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values
This is particularly useful if your object have no __dict__. If that is not the case you can try var(your_object) also
It’s often mentioned that to list a complete list of attributes you should use dir() . Note however that contrary to popular belief dir() does not bring out all attributes. For example you might notice that __name__ might be missing from a class’s dir() listing even though you can access it from the class itself. From the doc on dir() (Python 2, Python 3):
Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.
A function like the following tends to be more complete, although there’s no guarantee of completeness since the list returned by dir() can be affected by many factors including implementing the __dir__() method, or customizing __getattr__() or __getattribute__() on the class or one of its parents. See provided links for more details.
There is more than one way to do it:
When run, this code produces:
What do you want this for? It may be hard to get you the best answer without knowing your exact intent.
It is almost always better to do this manually if you want to display an instance of your class in a specific way. This will include exactly what you want and not include what you don’t want, and the order will be predictable.
If you are looking for a way to display the content of a class, manually format the attributes you care about and provide this as the __str__ or __repr__ method for your class.
If you want to learn about what methods and such exist for an object to understand how it works, use help . help(a) will show you a formatted output about the object’s class based on its docstrings.
dir exists for programatically getting all the attributes of an object. (Accessing __dict__ does something I would group as the same but that I wouldn’t use myself.) However, this may not include things you want and it may include things you do not want. It is unreliable and people think they want it a lot more often than they do.
On a somewhat orthogonal note, there is very little support for Python 3 at the current time. If you are interested in writing real software you are going to want third-party stuff like numpy, lxml, Twisted, PIL, or any number of web frameworks that do not yet support Python 3 and do not have plans to any time too soon. The differences between 2.6 and the 3.x branch are small, but the difference in library support is huge.
Python: Print an Object’s Attributes
In this tutorial, you’ll learn how to use Python to print an object’s attributes. Diving into the exciting world of object-oriented programming can seem an overwhelming task, when you’re just getting started with Python. Knowing how to access an object’s attributes, and be able to print all the attributes of a Python object, is an important skill to help you investigate your Python objects and, perhaps, even do a little bit of troubleshooting.
We’ll close the tutorial off by learning how to print out the attributes in a prettier format, using the pprint module!
Let’s take a look at what you’ll learn!
The Quick Answer: Use the dir() Function
Table of Contents
What are Python Objects?
Python is an object-oriented language – because of this, much of everything in Python is an object. In order to create objects, we create classes, which are blueprints for objects. These classes define what attributes an object can have and what methods an object can have, i.e., what it can do.
Let’s create a fairly simple Python class that we can use throughout this tutorial. We’ll create a Dog class, which will a few simple attributes and methods.
Let’s get started!
What we’ve done here, is created our Dog class, which has the instance attributes of name , age , and puppies , and the methods of birthday() and have_puppies() .
Let’s now create an instance of this object:
We now have a Python object of the class Dog , assigned to the variable teddy . Let’s see how we can access some of its object attributes.
What are Python Object Attributes?
In this section, you’ll learn how to access a Python object’s attributes.
Based on the class definition above, we know that the object has some instance attributes – specifically, name, age, and puppies.
We can access an object’s instance attribute by suffixing the name of the attribute to the object.
Let’s print out teddy’s age:
There may, however, be times when you want to see all the attributes available in an object. In the next two sections, you’ll learn how to find all the attributes of a Python object.
Use Python’s dir to Print an Object’s Attributes
One of the easiest ways to access a Python object’s attributes is the dir() function. This function is built-in directly into Python, so there’s no need to import any libraries.
Let’s take a look at how this function works:
We can see here that this prints out of all the attributes of a Python object, including the ones that are defined in the class definition.
The dir() function returns.a list of the names that exist in the current local scope returns the list of the names of the object’s valid attributes.
Let’s take a look at the vars() function need to see a more in-depth way to print an object’s attributes.
Use Python’s vars() to Print an Object’s Attributes
The dir() function, as shown above, prints all of the attributes of a Python object. Let’s say you only wanted to print the object’s instance attributes as well as their values, we can use the vars() function.
Let’s see how this works:
We can see from the above code that we’ve returned a dictionary of the instance attributes of our object teddy .
The way that this works is actually by accessing the __dict__ attribute, which returns a dictionary of all the instance attributes.
We can also call this method on the class definition itself. Let’s see how that’s different from calling it on an object:
We can see here that this actually returns significantly more than just calling the function on an object instance.
The dictionary also includes all the methods found within the class, as well as the other attributes provided by the dir() method.
If we wanted to print this out prettier, we could use the pretty print pprint module. Let’s see how we can do this:
You’ve now learned how to print out all the attributes of a Python object in a more pretty format!
Conclusion
In this post, you learned how to print out the attributes of a Python object. You learned how to create a simple Python class and how to create an object. Then, you learned how to print out all the attributes of a Python object by using the dir() and vars() functions. Finally, you learned how to use the pprint module in order to print out the attributes in a prettier format.
To learn more about the dir() function, check out the official documentation here.
How to get and print Python class Attributes
In this article, we are going to learn How to get and print Python class Attributes . The built-in attributes of a Python class and Python class Attribute how to get and print. When we declare a Python class, it comes with some built-in attributes that we get by default. These built-in attributes of Python classes are very useful and provide us a lot of information about that class. All these attributes have special representation and they all start with the double underscore “__”.
So let us start learning about these Python class Attributes in detail with the help of code examples.
First of all, let us see what are the attributes that we get in Python classes:
List of attribute in Python classes
1. __dict__ Dictionary
The Dictionary attribute of Python classes contains the information about the namespace to which this class belongs. Namespaces are the collections or modules scope definition that can include many classes inside it. So with the help of the Dictionary attribute, we can get this information about the class.
2. __doc__ Class documentation
Class documentation attribute gives us the class string doc information to us. This attribute gives us this information if this was defined by the person who wrote the class. If there is no string available in this then it returns none. In the class definition, class documentation is the very first line. This is not a mandatory requirement in class definition but it is good practice to have this. This helps others to understand what this class is about and what kind of functionality this class implements.
5.__bases__ Base class list
Inheritance is a very useful feature of OOPs and it provides us the concept of Base and derived classes. Base class list attributes help us to find out the Base class details of any class. It provides us this information as a tuple containing the base classes, in the order of their occurrence in the base class list. The object class is the base of all the classes in Python so this will return the object even if there is no base class defined by you.
Now let us jump to a Code example and demo of each of these class attributes. To start with, let us first define a class that we will use to understand all these attributes.