CanIgetallattributesthatweredefinedinthe__init__methodofaclass?

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 ?

回答

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'}

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

以上是CanIgetallattributesthatweredefinedinthe__init__methodofaclass?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>