pythonobject-model

In Python, what is the difference between an object and a dictionary?


After an object has been created, I can add and remove slots at will, as I can do with a dictionary. Even methods are just objects stored in slots, so I probably can add methods to a dictionary as well.

Is there something I can do with a (non-dictionary) object that I could never do with a dictionary? Or is it possible to set up a dictionary that completely looks like an object of a certain class?

This question is not about how they are created, but about how I can use them afterwards. Links or references are appreciated.


Solution

  • When you call member functions of an object, they get passed the object itself as a first parameter. This way they can modify properties of the object they belong to:

    class Counter(object):
       def __init__(self):
          self.num = 0
    
       def inc(self):
          self.num += 1
    
    count = Counter()
    count.inc()
    

    If you just store a bunch of functions in a dict, they will get no such support. You have to pass the dict around manually to achieve the same effect:

    def Counter_inc(d):
       d['num'] += 1
    
    def Counter_create():
       d = {
          'num': 0,
          'inc': Counter_inc,
       }
       return d
    
    count = Counter_create()
    count['inc'](count)
    

    As you can see while it is possible, it is much more clumsy. While you can emulate many features of object with raw dicts, having special language support for objects makes them easier to use.

    Also there are features that directly use an objects type information, like for example isinstance(), which cannot easily be replicated with raw dicts.