0

I recently noticed in Python that if I create a dict subclass I can add attributes, however this isn't the case with instances of dict. I.E:

class aDict(dict):
    pass

myDict = aDict({"name" : "A"})

myDict.color = "red"

print(myDict.color) #"red"

myOtherDict = dict({"name" : "B"})
myOtherDict.color = "green" #"AttributeError: 'dict' object has no attribute color"
mshsayem
  • 17,557
  • 11
  • 61
  • 69

1 Answers1

0

You are interacting with myDict's __dict__ which is the attribute dictionary given to an object, this is different to the myOtherDict which is the inbuilt dictionary. You can see the difference with how you interact with these by trying:

dir(myDict)
dir(myOtherDict)

and you can see what is accessible via myDict's dict attribute (and compare it with the lack of attribute on myOtherDict via vars()

vars(myDict)
vars(myOtherDict)

There's some more information available here and here that helped me to understand your problem.

Zooby
  • 325
  • 1
  • 7