4. classmethod

4.1. What it is?

  • Using class as namespace

  • Will pass class as a first argument

  • self is not required

4.2. When use it?

4.3. Example

import json


class JSONSerializable:
    def to_json(self):
        return json.dumps(self.__dict__)

    @classmethod
    def from_json(cls, data):
        data = json.loads(data)
        return cls(**data)


class User:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def __str__(self):
        return f'{self.first_name} {self.last_name}'

class Guest(User, JSONSerializable):
    pass

class Admin(User, JSONSerializable):
    pass


INPUT = '{"first_name": "Jan", "last_name": "Twardowski"}'

guest = Guest.from_json(INPUT)
admin = Admin.from_json(INPUT)

type(guest)     # <class '__main__.Guest'>
type(admin)      # <class '__main__.Admin'>

4.4. Assignments

4.4.1. Pickle

English
  1. Model class based on input data (see below)

  2. Create class PickleSerializable with methods .to_pickle() and .from_pickle()

  3. Use @classmethod decorator

  4. Create instances for input data

  5. Pickle data and write to file

  6. Unpickle data from file

Polish
  1. Zamodeluj klasę na podstawie danych wejściowych (patrz poniżej)

  2. Stwórz klasę PickleSerializable z metodami .to_pickle() i .from_pickle()

  3. Użyj dekoratora @classmethod

  4. Stwórz instancje dla danych wejściowych (see below)

  5. Spikluj dane do pliku

  6. Rozpikluj dane z pliku

Input Data
Mark, Watney, Astronaut
Jan, Twardowski, Cosmonaut
Melissa, Lewis, Astronaut
Ivan, Ivanovic, Cosmonaut