List attributes of an object [duplicate]
Is there a way to grab a list of attributes that exist on instances of a class?
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
a = new_class(2)
print(', '.join(a.SOMETHING))
The desired result is that "multi, str" will be output. I want this to see the current attributes from various parts of a script.
>>> class new_class():
... def __init__(self, number):
... self.multi = int(number) * 2
... self.str = str(number)
...
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])
You may also find pprint helpful.
dir(instance)
# or (same value)
instance.__dir__()
# or
instance.__dict__
Then you can test what type is with type()
or if is a method with callable()
.