Reputation: 3134
I'm relatively new to Python still, so feel free to let me know if there's something basic I'm missing.
In the interest of easy debugging, I've gotten in the habit of creating a show() procedure for every object I create. For example:
class YourMom:
def __init__(self):
self.name = ""
self.age = ""
self.children = []
#End init()
def show(self):
print "Name is '%s'" % (self.name)
print "Age is '%s'" % (self.age)
for i in self.children:
print " Children: '%s'" % (i)
#End show()
#End YourMom class
So my question is simple: Is there a programmatic way to do a show() procedure without needing to write it manually each time?
Edit: There is a similar question here: List attributes of an object But I'm looking for the VALUES in the object properties as well as the list of them.
Upvotes: 1
Views: 257
Reputation: 5059
As wim says, you can use vars
on any object with a __dict__
attribute. However, if you're dealing with an object that doesn't, you can use dir
. Note that this returns every single method and field associated with it, even ones like __eq__
and __ne__
.
If you type:
dir(YourMom())
into the interpreter, this is the result:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'children', 'name', 'show']
If you want to do anything more complicated than displaying everything, you'll probably want to check out inspect.
For example, if you only wanted to display attributes of the object that differ from any other object:
import inspect
a = YourMom()
# type is irrelevant below. comma after 'object' is critical,
# because the argument needs to be a tuple
plain_old_object = dir(type('plain', (object,), {}))
interesting_items = [item for item in inspect.getmembers(a) if item[0] not in plain_old_object]
This returns:
[('age', ''), ('children', []), ('name', ''), ('show', <bound method YourMom.show of <__main__.YourMom object at 0x02DC1B50>>)]
a
could be whatever type you want, honestly - it'd be really easy to turn this into a method that just takes an object and returns a list.
Upvotes: 1