Check out a free preview of the full Intermediate Python course
The "Class Methods" Lesson is part of the full, Intermediate Python course featured in this preview video. Here's what you'd learn in this lesson:
Nina introduces the class method, which is able to access the class variables on the type, rather than the instance.
Transcript from the "Class Methods" Lesson
[00:00:00]
>> Nina: If I wanted to track the number of wheels on my car.
>> Nina: And if you all are working in a file so that you can follow along with me, let me show you what I typed into the Repl.
>> Nina: And cars is the name of my py file without the py extension, just so you have that there.
[00:00:34]
Okay.
>> Nina: If I want to be able to access these class variables in my,
>> Nina: In my methods, I can provide something called a class method.
>> Nina: And those are defined with decorator like this. I'm not gonna go into too much detail, I just wanna show you because you might see those in other code.
[00:01:15]
The thing about the class method,
>> Nina: A class method doesn't take self. Instead, it takes a different argument called cls, or, it doesn't really matter what you name it, but this is kind of the convention. Now you can access,
>> Nina: Now you can access these class variables.
>> Nina: Oops, I want to return the number of wheels variable.
[00:01:54]
So it's saving that and reloading it. I can say my Subaru is a cars.car("subaru").
>> Nina: That's my instance.
>> Nina: I wasn't able to access the name from just the type. But now, because I made this a class method, I can say cars.Car and call get_number_of_wheels(). Notice, this is the type, not the instance.
[00:02:40]
It's the difference between a class method and an instance method. As you're just starting out, you'll probably be using all instance methods. Class methods are generally for special cases. You can also call these class methods on an instance, because,
>> Nina: The instance knows about the class, but not kind of the other way around.
[00:03:08]
So I still can't call .star, right? So if I try to call cars.Car.start(), this is expecting an instance, I don't have one. And I'm gonna get an error that says start() is missing 1 required positional argument of self.
>> Nina: So now you kind of know what some of these errors mean, where self is appearing from, kind of being binded under the hood by Python.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops