Question
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.).
How-To
You can leverage built-in API dir to know all attributes/methods/fields of an object. e.g.:
- >>> class Person:
- ... def __init__(self, name, age):
- ... self.name = name
- ... self.age = age
- ... def a(self):
- ... return self.age
- ... def n(self):
- ... return self.name
- ...
- >>> john = Person('John', 37)
- >>> john.a()
- 37
- >>> john.n()
- 'John'
- >>> dir(john)
- ['__doc__', '__init__', '__module__', 'a', 'age', 'n', 'name']
Then you can access the attribute(s) of an object by getattr:
- >>> for attr in john.__dict__.keys():
- ... if attr.startswith('__'):
- ... continue
- ... attr_obj = getattr(john, attr)
- ... if callable(attr_obj):
- ... print('attr \'{}\' is a function or method'.format(attr))
- ... else:
- ... print('attr of {} with value={}'.format(attr, attr_obj))
- ...
- attr of age with value=37
- attr of name with value=John
- >>> getattr(john, 'a')
0x7f0c64438d88 >>
Supplement
* How to get an attribute from an object in Python
沒有留言:
張貼留言