Python Memory Management and Tips Transcripts
Chapter: Memory and classes
Lecture: Concept: Slots
0:00 Let's review defining slots on classes.
0:02 It's incredibly easy. The thing on the left is a standard Python class. It has a
0:06 constructor like thing in Python, an initializer,
0:09 and it takes four fields and it's going to create them four parameters, it's gonna create
0:14 Those as fields, the names don't have to match,
0:16 but they happen to you this time. We're gonna create a "self.a" with that value,
0:19 self.b, c, and d.
0:21 If we want to have the better performance
0:24 and less memory usage of not having that dictionary,
0:27 we're going to use the keyword "slots". Over here, slot thing rather than regular thing,
0:32 same thing except we're gonna add "__slots__ equals the name of the fields: a,
0:36 b, c and d". You saw,
0:38 if you try to work with a field even in the initializer, that's not listed
0:42 here, it's gonna crash. As long as you do everything so it lines up,
0:45 this is a pretty good deal.
0:46 So over here we can create one of these objects. We can print down a value
0:50 like r.b will be 2.
0:53 And here we can even assign a new value r.e equals 7, and that
0:57 enters a new key in that dictionary.
0:59 It works, but it's probably a bad idea,
1:02 right? It's not very discoverable and whatnot.
1:04 It's very weird. But you can make it,
1:06 you can do this if you want the way Python is defined.
1:09 But with slots, you can see that the normal stuff works but this
1:13 creating a new field, like s.e equals 7, is an error.
1:17 In fact, what you'll get is "attribute
1:18 error: 'SlotThing' object has no attribute
1:21 'e'". I think this is a trade off for times when you're creating lots of
1:25 classes and you care about memory,
1:28 this is a really easy trade off to make.