-1

How do I enumerate over all attributes and instances of a class in Python?

This is the class:

class Human:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

This can't be a duplicate. I basically want to get a dictionary of all attributes name and their values and loop over the dictionary.

Roshan
  • 664
  • 5
  • 23
  • Attributes and instances are very different things... – tehhowch May 19 '19 at 05:46
  • You want `vars`; not sure of the best dup target (unless you're actually interested in finding all instances from the class. Ask that separately then, the answers are very different) – Nathan May 19 '19 at 05:48
  • 1
    Get the dictionary using __dict__. Create an instance of the class : `human = Human("Name", 123, "M")` then get the dictionary using `human.__dict__` –  May 19 '19 at 05:54
  • NewbieProgrammer, Thanks for your help. That indeed worked for me. Make it as an answer so that I can mark it. – Roshan May 19 '19 at 05:57
  • 2
    @Roshan... My answer has it plus a pointer to Python dataclasses. – sureshvv May 19 '19 at 05:58

1 Answers1

0

Every class has a __dict__ attribute which is a dictionary of all its attributes (plus some other special fields beginning with a double underscore.

So you can loop through __dict__ and ignore the keys starting with underscore.

You can also skip over callables if you just want attributes.

But may be you should be using a dataclass.

sureshvv
  • 4,234
  • 1
  • 26
  • 32