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 ?
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)
| 归档时间: |
|
| 查看次数: |
41 次 |
| 最近记录: |