How can I print to stdout the attributes and values of a class object? I've read this answer, but it's [mostly] not useful because the __dict__ method does not exist in Python 3.
And also vars does not return class attributes.
The solution I can find online seems to be to use the inspect standard library. But that's great when injecting class objects into functions. For example:
def get_class_obj_attrs(obj):
return inspect.getmembers(obj)
But I want a method on the class object that can return the attributes. I have come up with this as a solution:
class MyClass:
attr_1 = 0
def __init__(self, x):
self.attr_2 = x
def __getattrs__(self):
attrs = [i[0] for i in inspect.getmembers(self) if not i[0].startswith("_") and
not inspect.ismethod(i[1])]
return attrs
def __repr__(self):
return f"MyClass: { {attr: self.__getattribute__(attr) for attr in self.__getattrs__()} }"
So this can be used like:
my_class = MyClass()
print(my_class)
--> "MyClass: {'attr_1': 0, 'attr_2': 'foo'}"
The __getattrs__ method (not to be confused with default method __getattr__) depends on a library to function, so it's not ideal (even it is standard library).
What is the proper Python3 way of doing this, without having to jump through hoops? Surely there are built in methods?