0

When I try to add an entry to a dictionary within a class, it overrides dictionaries in all other instances of that class. Is there a way to make the dictionaries unique to each instance of the class?

class Object:
    dictionary = {}

    def __init__(self):
        return


a = Object()
a.dictionary["abc"] = "Hello, World!"

b = Object()
b.dictionary["abc"] = "Goodbye, World!"

print(a.dictionary["abc"])

In this example, it prints "Goodbye, World!". I would think a.dictionary and b.dictionary are two separate entities, so changing one should have no effect on the other. Is there a way I can have unique dictionaries for a and b so that I can manipulate one without affecting the other, so a.dictionary["abc"] is "Hello, World!" and b.dictionary["abc"] is "Goodbye, World!"?

1 Answers1

0

You have to define dictionary inside __init__(self).

class Object:

    def __init__(self):
        self.dictionary = {}

a = Object()
a.dictionary['abc'] = 'Hello, World!'


b = Object()
b.dictionary['abc'] = 'Goodbye World!'

print(a.dictionary['abc'])

If you define dictionary outside __init__(self), it will be common for all instances of Object (kind of like static variables in Java).

If you define it inside __init__(self), then it would be attributed to only a particular instance of an object, this is because, self would refer to that particular object in that case.

Shubham
  • 2,847
  • 4
  • 24
  • 37