为什么当我调用 class 的属性时,它打印的是旧变量而不是最新变量?

Why is it when I call an attribute of my class, it is printing an older variable instead of the latest one?

我目前正在使用 Python class 和方法,我有以下代码:

class Employee:
    def __init__(self, first,last):
        self.first = first
        self.last = last
        self.email = first + '.' + last + "@gmail.com"

    def fullname(self):
        return f'{self.first} + {self.last}'


emp_1 = Employee('John','Smith')
empl_1.first = 'Patrick'

print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname())

输出为:

Patrick
John.Smith@gmail.com
Patrick Smith

我很难理解的是,当我自己打印名字和员工的全名时,它使用的是最新的名字,定义为 'Patrick'。但是,对于电子邮件功能,它仍然使用'John'。谁能解释一下为什么会这样?

您只需定义一次 self.email - 在初始化对象时。它不会在您更改其他变量时神奇地更新。