Python Forum
Is there a better data structure than classes for a set of employes?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a better data structure than classes for a set of employes?
#6
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

Reply


Messages In This Thread
RE: Is there a better data structure than classes for a set of employes? - by buran - Feb-26-2020, 11:43 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Data structure question standenman 1 752 Jun-04-2023, 11:51 AM
Last Post: jefsummers
  Data saving structure JosefFilosopio 0 2,209 May-04-2019, 10:48 AM
Last Post: JosefFilosopio
  What data structure I need dervast 3 2,693 Apr-07-2019, 11:50 PM
Last Post: scidam
  Replacing values for specific columns in Panda data structure Padowan 1 14,769 Nov-27-2017, 08:21 PM
Last Post: Padowan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020