4

My logic goes like this:

def A(val):
    return {'a':val}

print(A(7)['a'])

is the same as

class A:
    def __init__(self, val):
        self.a = val

print(A(7).a)

Obviously, there are problems and some differences:

  • This only applies to languages like python where you can create a dictionary with different types in it.
  • The syntax of creating an 'object'. This is the reason (I think) classes are superior, because using a function to create classes would quickly become very irritating.
  • Special shortcut treatments. Like str(x) calls __str__ and obj.function() changes into cls.function(obj).
  • Inheritance.
  • Actual class objects (if A is the class, you can get A.__init__ (for example) as an unbound method.

Apart from these small cases, dictionaries == classes (to me). Do you agree with me?

  • What about the self argument of methods? Can you simulate this with a dictionary containing functions? – Giorgio Nov 10 '14 at 21:19
  • @Giorgio It is just a syntax shortcut. You would need to write a['func'](a) – user3808430 Nov 10 '14 at 21:23
  • True. In Python you always pass the current object as an extra argument anyway. – Giorgio Nov 10 '14 at 21:25
2

You can think of an object o as an entity containing

  1. a collection of local variables v1, v2, ... (the state of the object),
  2. a collection of closures m1, m2, ... that close over v1, v2, m1, m2 (the methods of the object),
  3. a mechanism to access the local variable and methods by name: an object is basically a higher-order function that takes a name as input and returns a field or a method as a result.

In a Python object you use the dot notation (o.var, o.foo()) to access members and methods. Of course, you can easily simulate this by means of a dictionary as you have described: a dictionary is also a mapping (see point 3) and you can use it to store object fields or methods.

So I would say that the class construct is a more convenient syntax to express the object pattern. You can simulate objects with dictionaries too, it just gets more verbose.

The syntax of creating an 'object'. This is the reason (I think) classes are superior, because using a function to create classes would quickly become very irritating.

Instead of having functions to create classes, I would imagine using functions to create objects (i.e. special dictionaries), which would correspond to class constructors. See also your example: function A() is the constructor function corresponding to the __init__() method of class A.

Inheritance.

I think that if you model classes with constructor functions returning dictionaries, then you can model inheritance by using the superclass constructor in the subclass constructor. The subclass constructor can call the superclass constructor and then extend / override the resulting dictionary with its own definitions.

For example:

# Superclass A.
def A(val):
    def toString(a):
        return str(a['a'])

    def printOut(a):
        print(a['toString'](a))

    return {'a': val, 'toString': toString, 'printOut': printOut}

# B is a subclass of A.
def B(val):
    # Override method.
    def toString(a):
        return 'value = ' + str(a['a'])

    r = A(val)
    r['toString'] = toString
    return r

Summarizing, I would not say that dictionaries are the same as classes:

  • A dictionary is an arbitrary mapping.
  • An object is a special mapping from names to variables and methods.
  • A class is a language construct that gathers together objects with similar structure and helps to create objects.
  • Objects and classes can be simulated in a straightforward way using functions and dictionaries.
4

You're right. Objects in dynamic languages evolved from, and in some ways resemble, fancy dictionary/mapping objects. This is very true for prototype-based languages like JavaScript, and still true for class-based languages like Python and Ruby.

However, the question is overly reductionistic. You ask "is there any difference?" only to quickly exclude quite a few very important differences. Capabilities like inheritance (Python has an elaborate multiple inheritance system with extensive metaclass support) and the special processing of dunder methods are not trifles. They're extensive bodies of work that define much of the language's semantics, operation, and extensibility.

You might want a listing of other ways Python classes are different, such as the the ability to

  1. Intervene at object creation time and systematically re-orchestrate how objects are created (metaclasses),
  2. Use static, non-dictionary representations (slots),
  3. Access members through attribute notation (obj.attr),
  4. Specialize functional attributes (aka methods) as virtual properties (@property), class rather than instance methods (@classmethod), or class-relative normal functions (@staticmethod).

We could list out even more ways that classes are different than mere "syntax sugar" on top of dictionaries. And the option to use a slotted, non-dictionary implementation should seal the deal. But such listings miss the number one issue:

Classes define new data types.

Classes and objects may be at some level just fancied dictionaries, but they're sufficiently evolved that they become something else entirely.

Classes define new data types. In all recent versions of the language--2.x forward, using "new style objects" that subclass object--user-defined classes are largely equivalent too, and fully parallel with, built-in data types. You can ask type(x) and instance(x, (int, str, MyClass)), interacting with classes and instances just as you do built-in datatypes and their values. That is not possible in most traditional static languages, where you may be able to build new abstract data types, but they will never, ever be comparable to, or as flexible as, the built-in types.

Full disclosure: There are a few remaining differences, largely subtle, and mostly based on the fact that built in types are implemented "under the covers" in C, and are not Python objects. per se.

But largely, classes are different from dictionaries in ways that pervade the language design, and that put them and their instances on par with language-define types. In Python, their similarity to mapping objects is decidedly secondary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.