In Python, is there any difference (apart from a few listed exceptions) between classes and dictionaries?

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?

3

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.

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật