如何遍历实例的方法以获取表示字符串

How to iterate through methods of instances to get a representation string

我正在尝试制作一个养老金税计算器并创建了一个 class“客户端”,它将接受来自两个不同用户的输入并根据这些输入计算他们的税金。

对于我遍历每个客户端,有没有比重复此代码更简洁的方法?

client1 = Client.from_input()
print(client1.name, 'Maximum pension contribution you can make this tax year: ', client1.get_maximum_contribution())
print(client1.name, 'Maximum pension contribution your employer can make this year: ', client1.get_carryforward() + client1.get_remaining_aa())
print(client1.name, 'Remaining annual allowance: ', client1.get_remaining_aa())
print(client1.name, 'Carryforward available: ', client1.get_carryforward())

client2 = Client.from_input()

print(client2.name, 'Maximum pension contribution you can make this tax year: ', client2.get_maximum_contribution())
print(client2.name, 'Maximum pension contribution your employer can make this year: ', client2.get_carryforward() + client1.get_remaining_aa())
print(client2.name, 'Remaining annual allowance: ', client2.get_remaining_aa())
print(client2.name, 'Carryforward available: ', client2.get_carryforward())

如果有人想要完整的代码或者它是否相关:

```# import datetime
# currentyear = datetime.date.today().year
# year3 = (datetime.date.today().year - 3)
# year2 = datetime.date.today().year - 2
# year1 = datetime.date.today().year - 1
aathreshold = 240000
aallowance = 40000
maxaareduction = 36000


class Client:
    def __init__(self, name, salary, bonus, intdiv, employeepercent, employerpercent, pensionlump, salaryexchange,
                 deathbenefits, year3contribution, year2contribution, year1contribution):
        self.name = name
        self.salary = salary
        self.bonus = bonus
        self.intdiv = intdiv
        self.employeecontribution = salary * (employeepercent / 100)
        self.employercontribution = salary * (employerpercent / 100)
        self.pensionlump = pensionlump
        self.salaryexchange = salaryexchange
        self.deathbenefits = deathbenefits
        self.totalgross = salary + bonus + intdiv
        self.totalannualpensioncontributions = self.employeecontribution + self.employercontribution + self.pensionlump
        self.year3contribution = year3contribution
        self.year2contribution = year2contribution
        self.year1contribution = year1contribution

    @classmethod
    def from_input(cls):
        return cls(input('Name: '),
                   int(input('Salary + Bonus: ')),
                   int(input('Bonus & Comission: ')),
                   int(input('Interest & Dividends: ')),
                   int(input('Employee gross workplace contribution % : ')),
                   int(input('Employer gross workplace contribution % :')),
                   int(input('Lump sum contributions: ')),
                   int(input('Employment income given through salary exchange')),
                   int(input('Taxed lump sum death benefits: ')),
                   int(input('Please enter your pension contributions for 2018: ')),
                   int(input('Please enter your pension contributions for 2019: ')),
                   int(input('Please enter your pension contributions for 2020: '))
                   )

    def get_carryforward(self):
        def cap_carryforward(contribution):
            if contribution > aallowance:
                contribution = aallowance
                remaining_allowance = aallowance - contribution
                return remaining_allowance
            else:
                remaining_allowance = aallowance - contribution
                return remaining_allowance

        year3remallowance = cap_carryforward(self.year3contribution)
        year2remallowance = cap_carryforward(self.year2contribution)
        year1remallowance = cap_carryforward(self.year1contribution)
        cf_allowance = year3remallowance + year2remallowance + year1remallowance
        return cf_allowance

    def get_threshold(self):
        threshinc = self.totalgross - self.pensionlump - self.employeecontribution\
                    + self.salaryexchange - self.deathbenefits
        return threshinc

    def get_adjustedincome(self):
        adjustedinc = self.totalgross + self.employercontribution - self.deathbenefits
        return adjustedinc

    def get_remaining_aa(self):
        taperexcess = 0
        if Client.get_adjustedincome(self) > aathreshold:
            taperexcess = (Client.get_adjustedincome(self) - aathreshold) / 2
            if taperexcess > maxaareduction:
                taperexcess = maxaareduction
        annualallowance = aallowance - taperexcess
        remaining_aa = annualallowance - self.totalannualpensioncontributions
        if remaining_aa <= 0:
            remaining_aa = 0
        return remaining_aa

    def get_maximum_contribution(self):
        combinedallowance = (Client.get_remaining_aa(self) + Client.get_carryforward(self))
        if (self.salary - combinedallowance) <= 0:
            maxcontribution = self.salary
            return maxcontribution
        elif (self.salary - combinedallowance) > 0:
            maxcontribution = combinedallowance
            return maxcontribution



client1 = Client.from_input()
print(client1.name, 'Maximum pension contribution you can make this tax year: ', client1.get_maximum_contribution())
print(client1.name, 'Maximum pension contribution your employer can make this year: ', client1.get_carryforward() + client1.get_remaining_aa())
print(client1.name, 'Remaining annual allowance: ', client1.get_remaining_aa())
print(client1.name, 'Carryforward available: ', client1.get_carryforward())

client2 = Client.from_input()

print(client2.name, 'Maximum pension contribution you can make this tax year: ', client2.get_maximum_contribution())
print(client2.name, 'Maximum pension contribution your employer can make this year: ', client2.get_carryforward() + client1.get_remaining_aa())
print(client2.name, 'Remaining annual allowance: ', client2.get_remaining_aa())
print(client2.name, 'Carryforward available: ', client2.get_carryforward())
def print_info_for_clients(clients):
    for client in clients:
        print(client.name, 'Maximum pension contribution you can make this tax year: ', client.get_maximum_contribution())
        print(client.name, 'Maximum pension contribution your employer can make this year: ', client.get_carryforward() + client.get_remaining_aa())
        print(client.name, 'Remaining annual allowance: ', client.get_remaining_aa())
        print(client.name, 'Carryforward available: ', client.get_carryforward())


client1 = Client.from_input()
client2 = Client.from_input()
print_info_for_clients([client1, client2])

如果你愿意,你可以将 Client.from_input() 移动到函数中,并传入一些客户端来读取,但我更喜欢这样做,因为我也可以分配 client1client2 以任意数量的不同方式,如果我愿意的话。

是的,您可以向 Client-class 添加一个 __str__ 方法来定义对象的字符串表示形式。例如:

import os
...
class Client:
    ...
    def __str__(self):
       line1 = f"{self.name} Maximum pension contribution you can make this tax year: {self.get_maximum_contribution()}"
       line2 = f"{self.name} Maximum pension contribution your employer can make this year:  {self.get_carryforward() + self.get_remaining_aa()}"
       line3 = f"{self.name} Remaining annual allowance:   {self.get_remaining_aa()}"
       line4 = f"{self.name} Carryforward available:   {self.get_carryforward()}"
       return os.linesep.join([line1,line2,line3,line4])

如果这样做,您只需在代码中执行 print(client1)。 或者,您可以将此方法命名为 getstring 并像这样 print(client1.getstring()).

如果您想遍历您的客户,您可以这样做:

client_list = [Client.from_input() for _ in range(num_clients)]
for client in client_list:
    print(client)

使用您的 from_input 方法创建 num_clients 的列表并将它们全部打印出来。

一个简单的 for 可能会起作用,具体取决于您想要多少个客户端:

def input_clients(how_many):
    clients = []
    for _ in range(how_many):
        client = Client.from_input()
        print(client.name, 'Maximum pension contribution you can make this tax year: ', client.get_maximum_contribution())
        print(client.name, 'Maximum pension contribution your employer can make this year: ', client.get_carryforward() + client.get_remaining_aa())
        print(client.name, 'Remaining annual allowance: ', client.get_remaining_aa())
        print(client.name, 'Carryforward available: ', client.get_carryforward())
        clients.append(client)
    return clients

input_clients(2)