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.).
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.
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.
__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.
Use the built-in function dir()
.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With