@classmethod explained in Python

preview_player
Показать описание
In this video I'm going to be teaching you how to use @classmethod in Python. As scary as it might look, it's very useful!

▶ Become job-ready with Python:

▶ Follow me on Instagram:
Рекомендации по теме
Комментарии
Автор

Imma tell you the best use for classmethod. One rule they don't tell you is: don't do work in init. It really makes your code more maintainable and extendable. So for instance (ha ha), say you have a class that is the data from a CCSDS packet in a data file.
Your procedural instinct is to have dunder init takes the file name and does the reading and unpacking there, and deriving the instance attributes. NO! DO NOT DO IT!!!.
Now with dataclasses, it's even easier---you define the CCSDS packet via the data class dunder init default, and the make a class method that is the all important "constructor helper":
@classmethod
def fromfilename(cls, fname, path=''):
with open(os.path.join(path, fname)) as fsrc:
return cls.fromefile(fsc)

@classmethod
def fromfile(cls, fsrc):
return cls(*fsrc.readlines())... # or some function thereof.

Trust me, it is much better.

DrDeuteron
Автор

I'm starting to get what @staticmethod and @classmethod does, but it's still a bit confusing. I guess I just need to practice more.

Thanks for the video. As usual, it's great!

facilvenir
Автор

This could also be a good opportunity to talk about properties and properties setters (I'm referring to the @property decorator). For example, you could access the total_cars attribute using a property and the instance could return the class value. Same thing for @property.setter, with that you would avoid mistakenly setting total_cars as an instance attribute but you'd explicitly refer to the class attribute. This was probably out of scope for the video though, it was very informative anyway! Well done 👏

ServantGrunt
Автор

you should never use the class name in an instance method, use "type(self)". If you need to know the exact class then it's time to, ugg, use name mangling.


and top speed of "200" is a magic number, it should be a private class attribute:
_top_speed = 200
in the class namespace.

DrDeuteron
Автор

you can also use class methods when calling a static method from inside a static method

tunakokarcali
Автор

Why can't you just use a function without self as a classmethod? Something like this
class X:
def __init__(self, x):
self.x = x

def class_method(x):
return X(x)

frobeniusfg
Автор

What is the scope of the class variables? Can i use it in differents modules for example?

miguelvasquez
Автор

Is there any reason you couldn't make a instance attribute of "self.total_cars = Car.total_cars"

class Car:
>total_cars: int = 0
>def init __ (self, brand: str, top_speed: int) -> None:
>>self.brand = brand
>>self.top_speed = top_speed
>>Car.total_cars += 1
>>self.total_cars = Car.total_cars


bmw: Car = Car(brand=""BMW", top_speed=50)
bmw.total_cars

teagancollyer