Python for .NET Developers Transcripts
Chapter: OOP: Object-Oriented Python
Lecture: Python class properties

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Properties are a wonderful addition to classes. Older versions of object oriented programming like C++ and Java in the early days
0:09 you had to have a get value and a set value or a get value if it was computed. For example, here we have a boolean property
0:17 which is whether or not the car's electric and we can compute that based off of the other information.
0:23 So here's our read-only computed property, that we can use and then over here we can say car.is_electric. And this is great
0:31 we treat it like a field, like it's just data and we don't have to treat it like it's behavior. Especially if you're modifying it
0:38 doing like ++ or something like that. Obviously it doesn't make sense for booleans but you know, if it was a number or something like that.
0:45 Can we do that in Python? How do we do it? Well, we don't have this get, set syntax but we do have the ability to have a property.
0:53 Let's do that in the very base car, here. And it has to do with these decorators. So, the way we use a decorator is to change what this does.
1:01 We also can use a decorator in a shortcut as well to create a method that is actually a property. Same thing that we had in C#.
1:11 Let's go, right is_electric, now we can compare. It will return self.engine_type == 'electric'. That's it, same thing.
1:23 So over here we have, going to say this is a read like, this implements the get, basically. The set is a little bit different.
1:30 It implements something that we can treat like a field or like data, but is actually a method that runs. So let's, over here, and we'll just print out.
1:48 We'll say, the car.model_name is electric question mark and then we'll just print out this property, like that.
1:54 And we run this, and bet is going to say you know, False, False, True, True, or something to that effect. Like, Corvette is electric, false.
2:03 Winstar is electric, false. Tesla electric, true. Bolt electric, true. How cool is that? So just like we have properties in C#
2:11 exactly the same thing, we have properties over here in these classes. And you define them like this. You say, app property on a regular method.
2:20 That defines the get. Obviously, it has to be a void method, right?


Talk Python's Mastodon Michael Kennedy's Mastodon