Klasy w Python-ie. Słownik z nieokreśloną liczbą par

Na podstawie: W3D1: Instantiating Class Objects with Hashes, Arg & Kwargs (3 of 4)

Tworzymy szkic ClassEmployee.py:

class Employee:
    def __init__(self, **employee_info):
        for item in employee_info:
            print(item)
new_employee = Employee(first_name='Jan', last_name='Kowalskil')

Wynik w terminalu po uruchomieniu programu:

first_name
last_name

Dodajemy linijkę:

print(dir(new_employee))

Zostają wyświetlone metody dostępne w klasie:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

Użyjemy metody __dict__

class Employee:
    def __init__(self, **employee_info):
        self.__dict__.update(**employee_info)

new_employee = Employee(first_name='Jan', last_name='Kowalskil')
print(dir(new_employee))

Wynik w terminalu po uruchomieniu programu:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'first_name', 'last_name']

Pojawiły się dwie dodatkowe metody ’first_name’, 'last_name’. Jeśli w obrębie klasy dodamy dodatkową funkcję say_hello() wszystko zaczyna działać

class Employee:
    def __init__(self, **employee_info):
        self.__dict__.update(**employee_info)
    def say_hello(self):
        return f"Hello, my name is {self.first_name} {self.last_name}"
new_employee = Employee(first_name='Jan', last_name='Kowalski
print(new_employee.say_hello())

Wynik w terminalu po uruchomieniu programu:

> Hello, my name is Jan Kowalski

Alternatywne tworzenie słownika z dowolną ilością elementów. Ta wersja działa z MicroPython-em na ESP32. Podana wyżej z powodu braku modułu __dict__ zgłasza błąd

class Employee:
    def __init__(self, **employee_info):
        for key, value in employee_info.items():
            setattr(self, key, value)
    def say_hello(self):
        return f"Hello, my name is {self.first_name} {self.last_name}"

new_employee = Employee(first_name='Jan', last_name='Kowalski')
print(new_employee.say_hello())

Dodaj komentarz