When I define a class with variables already assign, instantiate it and use __dict__
to get variables as a dictionary, I get an empty list.
In [5]:
class A(object):
a = 1
b = 2
text = "hello world"
def __init__(self):
pass
def test(self):
pass
x = A()
x.__dict__
Out[5]:
{}
But when I declare variables in __init__
and use __dict__
it returns variables which were assigned after instantiation of class.
In [9]:
class A(object):
a = 1
def __init__(self):
pass
def test(self):
self.b = 2
self.text = "hello world"
x = A()
x.test()
x.__dict__
Out[9]:
{'b': 2, 'text': 'hello world'}
Why is that __dict__
returning only variables declared after instantiation of class
Edit Answer:
When an instance is created like x = A()
x.__dict__
stores all the instance attributes.
A.__dict__
stores the class attributes