Python for the .NET developer Transcripts
Chapter: OOP: Object-Oriented Python
Lecture: Concept: Python interfaces and magic methods
0:00 While Python itself doesn't have separate interfaces
0:03 outside of the concept of just maybe
0:05 an abstract base class
0:06 you did see that there are certain types of functions
0:09 we can optionally implement
0:11 that have the same basic effect.
0:13 For example, our parking lot
0:15 we wanted to be able to use it in a for in loop.
0:17 How do we do that?
0:18 Well, we have to add the __iter__ method here.
0:22 And that was super easy. We just created a little generator.
0:24 We said for item in self.spot.items
0:27 yield item, right?
0:28 No big deal for us to do that
0:30 yet this is how we were able to use the lot
0:33 within a for in loop to get those items back out.
0:36 This method here, this __iter__
0:39 this is Python's equivalent of what would happen in C#
0:43 if you implement IEnumerable<T>.
0:46 There are tons of these special methods.
0:50 There's actually a guide over here by Rafe Kettler
0:53 who did a really nice job of combing through each one
0:55 explaining what it does what it's about
0:58 when you use it, and so on.
0:59 This is a huge long article.
1:01 I don't want to go through all of them.
1:02 I just touched on a few of the key ones
1:04 __str__, __init__, __iter__, __repr__, alright.
1:08 There's a bunch more that you'll want to know about
1:10 or at least know that they exist
1:12 and then you go learn about 'em
1:13 like, Oh, I actually probably could implement this
1:15 and, you know, make it do whatever it is
1:17 you're trying to do. Our parking lot now
1:20 effectively, in like C# terminology
1:23 implements IEnumerable
1:24 by using this magic method
1:25 which they're sometimes called, or dunder method.