Skip to main content
 首页 » 编程设计

python之即使我清楚地为其分配了不同的值,方法属性也不会自行更新

2025年05月04日14grandyang

<分区>

更新值后,__init__ 方法仍使用旧属性值。

class Email: 
    def __init__(self, name): 
        self.name = name 
        self.email = self.name + "@hotmail.com" 
 
    def details(self): 
        return f'{self.name} | {self.email}' 
 
person = Email("James") 
print(person.details()) 
 
person.name = "Michael" 
print(person.details()) 

得到的输出:

James | James@hotmail.com 
Michael | James@hotmail.com 

预期输出:

James | James@hotmail.com 
Michael | Michael@hotmail.com 

我做错了什么?