2

I have a class that looks somthing like this:

class A(dict):
  info = {'num': 0}
  def __init__(self, **kwargs):
    self.__dict__.setdefault('info', self.info)

When I'm creating instances of this class they referenced to the same object:

>>> a = A()
>>> b = A()
>>> 
>>> b.info['num']
0
>>> a.info['num'] = 1
>>> b.info['num']
1
>>> 

I'm clearly doing something wrong.

Problems:

  1. Instances of a and b are referenced to the same object.

Desired output:

>>> a = A()
>>> b = A()
>>> 
>>> b.info['num']
0
>>> a.info['num'] = 1
>>> b.info['num']
0
>>> 

Question:

  1. How to change the class in order to keep this "template" of info?
  2. Why the current approuch doesn't work?
Vor
  • 33,215
  • 43
  • 135
  • 193

0 Answers0