Search code examples
pythonpython-3.xclassattributesintrospection

Can I get all attributes that were defined in the __init__ method of a class?


Suppose I have a class like this:

class A:
    def __init__(self):
        self.a = "a"
        self.b = "b"

How would I get a dictionary like this ?

{"a": "a", "b": "b"}

I read this question and answers, but the dictionary in these answers always contains some "dunder" attributes as well, which I never defined in A.__init__. Will I have to use one of the solutions in the linked question and filter out the dunder attributes, or is there a smarter way ?


Solution

  • You can do this by looking at the __dict__ attribute or using the vars function like so:

    class A:
        def __init__(self):
            self.a = "a"
            self.b = "b"
    
    print(A().__dict__)  # prints {'a': 'a', 'b': 'b'}
    print(vars(A()))     # also prints {'a': 'a', 'b': 'b'}