dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

Saving data structures using slots #69

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

Usually Python devs store data structures in dictionaries. A more efficient way is to use "slotted objects". A slotted object is a class which has the slots attributed defined. In the interest of space, the typical class dict attribute is removed.

Example of a slotted object:

class DemoObject(object):   # Note we subclass "object" to remove the __dict__ attr
    __slots__ = ('a', 'b', 'c')

demo1 = DemoObject()
demo1.a = 1
demo1.b = 2

Slotted objects have a couple of advantages over dicts:

Caveats:

dvas0004 commented 5 years ago

https://stackoverflow.com/questions/472000/usage-of-slots