You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写获取最高薪资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: WorkerService shouldn't inherit from Worker—it's a service class meant to manage Worker instances, not a type of Worker itself.
  • Type annotation error: The workers class variable in WorkerService has incorrect syntax. It should be a type hint, not an assignment like workers = list[Worker].
  • Indentation mistake: The __str__ method in Worker is indented inside data_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

  1. Service Class Fix: WorkerService now holds a list of Worker instances as an instance variable—you initialize it when creating a WorkerService object (e.g., service = WorkerService([worker1, worker2])).
  2. Edge Case Handling: We added a check for empty worker lists to avoid a ValueError from the max() function, and return None with a warning instead of crashing.
  3. Efficient Salary Comparison: The max() function uses a lambda as the key parameter, which tells Python to rank each worker by their salary attribute. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 10:35:41