开发者社区> 问答> 正文

如何添加对函数的调用?

total_pay是父类Employee的方法,SalariedEmployee和HourlyEmployee是其子类。

我知道我想做什么,我只是不知道怎么做。我想在之前的pay方法调用中添加所有付款变量。我如何访问以前的电话?更具体地说,付费方式中的付款对象。

class Employee:

"""An employee of a company.
This is an abstract class. Only child classes should be instantiated.

=== Public attributes ===
id_: This employee's ID number.
name: This employee's name.
"""
id_: int
name: str

def __init__(self, id_: int, name: str) -> None:
    """Initialize this employee.

    Note: This initializer is meant for internal use only;
    Employee is an abstract class and should not be instantiated directly.
    """
    self.id_ = id_
    self.name = name
    self.counter = 0

def get_monthly_payment(self) -> float:
    """Return the amount that this Employee should be paid in one month.

    Round the amount to the nearest cent.
    """
    raise NotImplementedError

def pay(self, pay_date: date) -> None:
    """Pay this Employee on the given date and record the payment.

    (Assume this is called once per month.)
    """
    payment = self.get_monthly_payment()
    print(f'An employee was paid {payment} on {pay_date}.')

def total_pay(self) -> float:
    """Return the total amount of pay this Employee has received.

    >>> e = SalariedEmployee(14, 'Gilbert the cat', 1200.0)
    >>> e.pay(date(2018, 6, 28))
    An employee was paid 100.0 on 2018-06-28.
    >>> e.pay(date(2018, 7, 28))
    An employee was paid 100.0 on 2018-07-28.
    >>> e.pay(date(2018, 8, 28))
    An employee was paid 100.0 on 2018-08-28.
    >>> e.total_pay()
    300.0
    """

在多次调用pay方法之后,total_pay方法应该返回所有这些值的总和。可以假设付费方式每月只调用一次。

展开
收起
一码平川MACHEL 2019-01-23 11:01:08 3216 0
1 条回答
写回答
取消 提交回答
  • 您需要以某种方式保存数据以检索它。

    这是一个非常抽象的问题,有很多方法可以实现它。

    但要回答你的问题:

    如何访问之前的调试?

    你不能,代码被执行,没有什么可以“访问”。

    更具体地说,付费方式中的付款对象。

    这是正确的问题。在您当前的代码中,付款变量将分配给付款对象。但是在函数完成后,python的垃圾收集将从内存中删除对象,因为它的最后一个引用不再附加到任何活动范围。

    如果要访问该对象,则需要在其中创建对象的引用,该引用self是对象的实例。

    因此,一种解决方案是拥有self被调用的属性payments,这是一个列表,附加到新的付款。

    但是,您将从pay中丢失date参数,因此您可能希望将其作为dict使用日期作为键或dicts数组。或任何数量的其他数据结构。

    所以在初始化中,你会有类似的东西self.payments = [],并付出类似的东西self.payments.append((pay, date)),我会让你弄清楚你想如何总结列表中的数据。

    2019-07-17 23:26:33
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
建立联系方法之一 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多