How To Get Attributes Of Object In Python

This is just a tips.

GOAL

To get the list of attributes of an object in Python

Environment

Python 3.7.4

Method

Use built-in function dir([object]) method as below.

dict1 = {"a":1, "b":2}
print(dir(dict1))
# output => ['__class__', '__contains__', '__delattr__', ... , 'setdefault', 'update', 'values']

dir() can takes not only variable but also any objects such as ‘type’ itself.

print(dir(dict))
# output is the same as print(dir(dict1)) above 

dir() can be used for user-defined class, too.

class User:
    number = 0
    def __init__(self, name, age=0):
        self.name = name
        self.age = 0
        self.addNum()
    def profile(self):
        print("Name:"+self.name, " Age:"+self.age)
    @classmethod
    def addNum(cls):
        cls.number += 1g

user1 = User("John", 20)
print(dir(user1))
# output => ['__class__', '__delattr__', '__dict__', ... , 'addNum', 'age', 'name', 'number', 'profile']

dir([object]) function return the list of only the object’s attributes. So the list returned by dir(User) includes class variables “number” but don’t include instance variables “name” and “age”.

 class User:
    number = 0
    def __init__(self, name, age=0):
        self.name = name
        self.age = age
        self.addNum()
    def isAdult(self):
        if 18 <= self.age:
            return True
        else:
            return False
    def profile(self):
        print("Name:"+self.name, " Age:"+self.age)
    @classmethod
    def addNum(cls):
        cls.number += 1

print(dir(User))
# output => ['__class__', '__delattr__', '__dict__', ... , 'addNum', 'number', 'profile']

If dir() takes no argument, it returns the list of names in the current local scope.

user1 = User("John", 20)
num1 = 10
dict1 = {"a":1, "b":2}
print(dir())
# output => ['User', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'dict1', 'num1', 'user1']

Appendix

Module “inspect” is also used for getting information of objects as below.

import inspect
user1 = User("John", 20)
print(inspect.getmembers(user1))
# getmembers returns the pairs of (attribute, its value)
# output => [('__class__', <class '__main__.User'>), ('__delattr__', <method-wrapper '__delattr__' of User object at 0x000002B8A1BBAEB0>), ('__dict__', {'name': 'John', 'age': 20}), ... , ('name', 'John'), ('number', 1), ('profile', <bound method User.profile of <__main__.User object at 0x000002B8A1BBAEB0>>)]

Function vars([object]) only return __dict__ attributes of the object that is the dict of (variables, value).

user1 = User("John", 20)
print(vars(user1))
# output => {'name': 'John', 'age': 20}