Is there a built-in function to print all the current properties and values of an object?
In Python, you can use the built-in function vars()
to print the properties and values of an object. vars()
returns the __dict__
attribute of an object, which is a dictionary containing the object's attributes and their values.
Here's an example:
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
obj = MyClass(1, 2)
print(vars(obj))
This will output:
{'x': 1, 'y': 2}
Watch a video course
Python - The Practical Guide
You can also use dir()
function to get a list of an object's attributes, including methods and properties.
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
obj = MyClass(1, 2)
print(dir(obj))
Additionally, __dict__
is also python built in property which can be used to return the attribute dict of an object
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
obj = MyClass(1, 2)
print(obj.__dict__)
Both of this will output something like
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'x', 'y']
It will show all the attributes of the object including the built-in methods, This can be useful when you want to get the name of attributes as well