How to use  __dict__() Magic Method In Python

To find attributes we can also use magic method __dict__. This method only returns instance attributes.

Example: 

Python3




class Number :
     
    # Class Attributes
    one = 'first'
    two = 'second'
    three = 'third'
     
    def __init__(self, attr):
        self.attr = attr
         
    def show(self):
        print(self.one, self.two,
              self.three, self.attr)
         
# Driver's code
n = Number(2)
n.show()
 
# using __dict__ to access attributes
# of the object n along with their values
print(n.__dict__)
 
# to only access attributes
print(n.__dict__.keys())
 
# to only access values
print(n.__dict__.values())


Output: 

first second third 2
{'attr': 2}
dict_keys(['attr'])
dict_values([2])

How to Get a List of Class Attributes in Python?

A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state. 

Example: 

Python3




# Python program to demonstrate
# classes
 
 
class Student:
  
 # class variable
 stream = "COE"
  
 # Constructor
 def __init__(self, name, roll_no):
   
  self.name = name
  self.roll_no = roll_no
   
# Driver's code
a = Student("Shivam", 3425)
b = Student("Sachin", 3624)
 
print(a.stream)
print(b.stream)
print(a.name)
print(b.name)
 
# Class variables can be accessed
# using class name also
print(Student.stream)


Output : 

COE
COE
Shivam
Sachin
COE

Note: For more information, refer to Python Classes and Objects.

Similar Reads

Getting a List of Class Attributes

...

Using built-in dir() Function

It is important to know the attributes we are working with. For small data, it is easy to remember the names of the attributes but when working with huge data, it is difficult to memorize all the attributes. Luckily, we have some functions in Python available for this task....

Using getmembers() Method

To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir()....

Using  __dict__() Magic Method

...

Using vars() function

Another way of finding a list of attributes is by using the module inspect. This module provides a method called getmembers() that returns a list of class attributes and methods....