5.4. classmethod

5.4.1. What it is?

  • Using class as namespace

  • Will pass class as a first argument

  • self is not required

5.4.2. When use it?

5.4.3. Examples

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


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

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

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

5.4.4. Assignments

5.4.4.1. Protocol Classmethod

English
  1. Use data from "Input" section (see below)

  2. Model class based on input data

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

  4. Use @classmethod decorator

  5. Create instances for input data

  6. Pickle data and write to file

  7. Unpickle data from file

Polish
  1. Użyj danych z sekcji "Input" (patrz poniżej)

  2. Zamodeluj klasę na podstawie danych wejściowych

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

  4. Użyj dekoratora @classmethod

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

  6. Spikluj dane do pliku

  7. Rozpikluj dane z pliku

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