为什么此类中的函数不使用更新的类属性?

2024-10-02 06:24:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如下所示,更新类属性不会更改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”


Tags: 函数self属性initemaildefemployeescott
2条回答

在创建emp_1期间,您仅在init函数中计算self.email。当您最后更改emp_1.last时,它不会重新触发计算电子邮件的行。通过为电子邮件添加功能,您可以获得所需的行为:

def email(self):
    return self.first + '.' + self.last + '@company.com'

...

print(emp_1.email())

如果您想要此行为,您需要将email转换为^{}(并且您可能应该对fullname执行相同的操作):

class Employee:
    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return self.first + "." + self.last + "@company.com"
        # return f"{self.first}.{self.last}@company.com"

    @property
    def fullname(self):
        return "{} {}".format(self.first, self.last)
        # return f"{self.first} {self.last}"

这将如预期的那样起作用:

emp_1 = Employee('Micheal', 'scoot', 50000)
emp_1.last = 'Scott'        
print(emp_1.email)       # -> Micheal.Scott@company.com 
print(emp_1.fullname)    # now without parentheses! -> Micheal Scott

在原始代码中,在构造函数中指定self.email。这样,如果您在之后更改self.last,它将不会得到更新

相关问题 更多 >

    热门问题