Get all object attributes in Python?

StackOverflow

Is there a way to get all attributes/methods/fields/etc. of an object in Python?

vars() is close to what I want, but it doesn"t work unless an object has a __dict__, which isn"t always true (e.g. it"s not true for a list, a dict, etc.).

Answer rating: 652

Use the built-in function dir().

Answer rating: 112

I use __dict__ and dir(<instance>)

Example:

class MyObj(object):
  def __init__(self):
    self.name = "Chuck Norris"
    self.phone = "+6661"

obj = MyObj()
print(obj.__dict__)
print(dir(obj))

# Output:  
# obj.__dict__ --> {"phone": "+6661", "name": "Chuck Norris"}
#
# dir(obj)     --> ["__class__", "__delattr__", "__dict__", "__doc__",
#               "__format__", "__getattribute__", "__hash__", 
#               "__init__", "__module__", "__new__", "__reduce__", 
#               "__reduce_ex__", "__repr__", "__setattr__", 
#               "__sizeof__", "__str__", "__subclasshook__", 
#               "__weakref__", "name", "phone"]

Answer rating: 62

You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values

usage :

for att in dir(your_object):
    print (att, getattr(your_object,att))




Get Solution for free from DataCamp guru