PythiloLesson 9 of 30 · progress kept in this browser

Class and static methods

A normal method receives the instance as self. Two decorators change what a method receives.

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    @classmethod
    def from_text(cls, text):
        x, y = text.split(",")
        return cls(int(x), int(y))

    @staticmethod
    def is_valid(text):
        return text.count(",") == 1

class Pixel(Point):
    pass

p = Pixel.from_text("3,4")
print(type(p).__name__, p.x, p.y)
print(Point.is_valid("1,2"))
Your task

Write Color(r, g, b) that limits each channel to 0..255 with a static method clamp(value), a class method from_hex(text) turning "#ff8000" into the matching color of whichever class it is called on, and a repr like Color(255, 128, 0) that uses the instance's own class name.

Next: Dataclasses