employees.yaml
Output: - name: John
nationality: USA
- name: Jane
nationality: UK
import yaml from random import randint from dataclasses import dataclass # one way to define basic class class Employee: def __init__(self, name, nationality): self.name = name self.nationality = nationality @property def cost(self): some_calculated_cost = randint(0, 20) # here I just randomly genereate cost between 0 and 20 return some_calculated_cost # alternative, using @dataclass @dataclass class Employee2: name: str nationality: str @property def cost(self): some_calculated_cost = randint(0, 20) # here I just randomly genereate cost between 0 and 20 return some_calculated_cost if __name__ == '__main__': # load using Employee class with open('employees.yaml') as f: employees = [Employee(**empl) for empl in yaml.safe_load(f)] # load using Employee2 class with open('employees.yaml') as f: employees2 = [Employee2(**empl) for empl in yaml.safe_load(f)] print(employees) # this one has no __str__ or __repr__ method defined print(employees2) # note the difference, this one has __repr__() method autocreated for employee in employees: print(f'{employee.name}: {employee.cost}') for employee in employees: print(f'{employee.name}: {employee.cost}')
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs