Python class method

whitehousechef·2025년 7월 7일

Class method vs normal method

Class method is like static method, no need instance unlike normal method

# You'd have to do this manually every time:
def get_seat_type(short_code):
    if short_code == 'R':
        return SeatType.REGULAR
    elif short_code == 'P':
        return SeatType.PREMIUM
    elif short_code == 'V':
        return SeatType.VIP
    else:
        raise ValueError(f"Invalid: {short_code}")
        
@classmethod
def from_short(cls, short_code: str) -> 'SeatType':
    # cls = the class itself (SeatType)
    # This loops through ALL possible SeatType values
    for seat_type in cls:  # cls is SeatType class
        if seat_type.short == short_code:
            return seat_type
    raise ValueError(f"Invalid seat type: {short_code}")

0개의 댓글