python get class attributes code example

Example 1: get object attributes python

for att in dir(your_object):
    print (att, getattr(your_object,att))

Example 2: python get class

x.__class__.__name__

Example 3: python get attributes of object

getattr(object, 'attribute_name')

Example 4: see attributes of object python

>>> 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'])

Example 5: python get attributes of class

import inspect

class myclass:
  a = 5
  def method(b):
    return b

for i in inspect.getmembers(myclass):
  print(i)

Example 6: how to get all values from class in python

>>> an = Animal()
>>> attrs = vars(an)
#{'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}