0

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

Harwee
  • 1,601
  • 2
  • 21
  • 35

1 Answers1

2

Pls try A.__dict__ to get all class attributes,

x = A()
x.__dict__

here you are calling __dict__ method on A's instance. So the variables associated with that instance should be displayed...

self.b, self.text are instance variables which are specific to particular instance only..

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274