Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all object attributes in Python? [duplicate]

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

like image 377
user541686 Avatar asked Jul 30 '11 23:07

user541686


People also ask

How do I see all the attributes of an object in Python?

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.

How do you print the attributes of an object in Python?

To print the attributes of an object we can use “object. __dict__” and it return a dictionary of all names and attributes of object. After writing the above code (python print object attributes), once you will print “x. __dict__” then the output will appear.

What is __ Getattribute __ in Python?

__getattribute__This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.


2 Answers

Use the built-in function dir().

like image 73
mouad Avatar answered Oct 09 '22 22:10

mouad


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'] 
like image 22
Slipstream Avatar answered Oct 09 '22 22:10

Slipstream