Home > front end >  Python Class with input data
Python Class with input data

Time:01-19

I want to create a function to get the worker with the biggest salary. How can I write it?

dataclasses import dataclass
from decimal import Decimal
from typing import Self


@dataclass
class Worker:
    name: str
    surname: str
    age: int
    salary: Decimal

    @classmethod
    def data_input(cls):
        return cls(
            name=input('Name:\n'),
            surname=input('Surname:\n'),
            age=int(input('Age:\n')),
            salary=Decimal(input('Decimal:\n'))

        )

        def __str__(self):
            return f'{self.name}, {self.surname}, {self.age}, {self.salary}'
    
    
    @dataclass
    class WorkerService(Worker):
        workers = list[Worker]
    
        def get_worker_with_biggest_salary(self, workers: workers) -> Self:
            return 

CodePudding user response:

So to directly answer your question I would use the max built-in to get the largest salary.

class WorkerService:
    workers: list[Worker]

    def get_worker_with_biggest_salary(self):
        return max(self.workers, key=lambda worker: worker.salary)

    def __init__(self):
        self.workers = list()

However I would add that WorkerService should not be a dataclass. Dataclasses are suppose to hold information and that is about it. If you class has a bunch of functions that manipulate its state then it should just be a class and not a dataclass

Also for Worker you have a function called data_input. dataclass already lets you create the class that way. You should instead move input handling out of the class and then create the instance with what is inputted. Also WorkerService has an instance field called workers yet when you wrote get_worker_with_biggest_salary you take in an argument of workers. You should either take in the argument or use add_worker or remove_worker and then work off the instance field. Heres an example...

name = input('Name:\n'),
surname = input('Surname:\n'),
age = int(input('Age:\n')),
salary = Decimal(input('Decimal:\n'))

worker = Worker(
    name=name,
    surname=surname,
    age=age,
    salary=salary
)

worker_service.add_worker(worker)

highest_salary_worker = worker_service.get_worker_with_biggest_salary()
  • Related