如下所示,更新类属性不会更改init函数中使用的属性的值,但会更改以下类函数中使用的值。为什么会这样
我刚开始修补课程,所以我不确定要尝试什么替代方案
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('Micheal', 'scoot', 50000)
emp_1.last = 'Scott'
print(emp_1.email) # - > Micheal.scoot@company.com
print(emp_1.fullname()) # - > Micheal Scott
上面的注释显示了我收到的输出。我希望电子邮件功能使用更新后的姓“Scott”而不是“scoot”
在创建emp_1期间,您仅在init函数中计算self.email。当您最后更改emp_1.last时,它不会重新触发计算电子邮件的行。通过为电子邮件添加功能,您可以获得所需的行为:
如果您想要此行为,您需要将} (并且您可能应该对
email
转换为^{fullname
执行相同的操作):这将如预期的那样起作用:
在原始代码中,在构造函数中指定
self.email
。这样,如果您在之后更改self.last
,它将不会得到更新相关问题 更多 >
编程相关推荐