如何编写获取最高薪资Worker对象的Python函数?
Hey there! Let's work through this problem step by step. First, I notice a few small issues in your existing code that we should fix before implementing the salary method, then we'll tackle the get_worker_with_biggest_salary function properly.
Issues in the Original Code
- WorkerService inheritance:
WorkerServiceshouldn't inherit fromWorker—it's a service class meant to manage Worker instances, not a type of Worker itself. - Type annotation error: The
workersclass variable inWorkerServicehas incorrect syntax. It should be a type hint, not an assignment likeworkers = list[Worker]. - Indentation mistake: The
__str__method inWorkeris indented insidedata_input, which means it's not part of the Worker class at all. - Minor typo: The input prompt for salary says "Decimal" instead of "Salary"—that's confusing for users.
Fixed Code with the Implemented Method
from dataclasses import dataclass from decimal import Decimal from typing import List, Optional @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('Salary:\n')) ) def __str__(self): return f'{self.name} {self.surname}, Age: {self.age}, Salary: {self.salary}' @dataclass class WorkerService: # Store workers as an instance variable for the service workers: List[Worker] def get_worker_with_biggest_salary(self) -> Optional[Worker]: # Handle empty list case to avoid crashing if not self.workers: print("Warning: No workers in the list to compare salaries.") return None # Use Python's built-in max() with a key to compare salaries return max(self.workers, key=lambda worker: worker.salary)
How It Works
- Service Class Fix:
WorkerServicenow holds a list ofWorkerinstances as an instance variable—you initialize it when creating aWorkerServiceobject (e.g.,service = WorkerService([worker1, worker2])). - Edge Case Handling: We added a check for empty worker lists to avoid a
ValueErrorfrom themax()function, and returnNonewith a warning instead of crashing. - Efficient Salary Comparison: The
max()function uses a lambda as thekeyparameter, which tells Python to rank each worker by theirsalaryattribute. This is concise and leverages Python's optimized built-in functions.
Alternative: Method Accepts Workers as a Parameter
If you prefer the method to take the workers list directly as an argument (instead of using the service's instance variable), you can adjust it like this:
def get_worker_with_biggest_salary(self, workers: List[Worker]) -> Optional[Worker]: if not workers: print("Warning: No workers in the list to compare salaries.") return None return max(workers, key=lambda worker: worker.salary)
内容的提问来源于stack exchange,提问作者JimmyJones
相关产品推荐
相关产品推荐

