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

Viewed 563

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 ?

3 Answers

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'}
class A:
    foo = 'bar'

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

a = A()
print(vars(a)) # prints "{'a': 'a', 'b': 'b'}"
print({k: v for k, v in vars(A).items() if not k.startswith('__')}) # prints "{'foo': 'bar'}"

Perhaps I'm not understanding your question, but the easiest method for getting a dictionary of attributes like you described is as follows:

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

x = A()

print(x.__dict__)

This should give you:

{a: "A", b: "B"}

The dict attribute is a dunder attribute, but it is the most elegant solution for this IMO. Is there a specific reason you'd like to avoid this method? If not, I recommend it for simplicity's sake.

Related