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

Pro*_*mer 0 python attributes class introspection python-3.x

Suppose I have a class like this:

class A:
    def __init__(self):
        self.a = "a"
        self.b = "b"
Run Code Online (Sandbox Code Playgroud)

How would I get a dictionary like this ?

{"a": "a", "b": "b"}
Run Code Online (Sandbox Code Playgroud)

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 ?

Pir*_*jas 5

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'}
Run Code Online (Sandbox Code Playgroud)

  • 事实上,给定`a = A()`,`a.__dict__ is vars(a)` 应该是真的。 (2认同)