__dict__对于未显示@property属性的对象

使用装饰器时,我通过“setter”装饰器设置一个属性,但是它没有显示在对象的dict 中。下面是我的代码

class Employee:
    def __init__(self, first, last):
        self.f_name = first
        self.l_name = last
        self.email = self.f_name + '.' + self.l_name + '@hotmail.com'
    
    @property
    def fullname(self):
        return ('{} {}'.format(self.f_name,self.l_name) )


    @fullname.setter
    def fullname(self, name):
        first, last = name.split(' ')
        self.f_name = first
        self.l_name = last
        self.email = self.f_name + '.' + self.l_name + '@hotmail.com'
        
emp_1 = Employee('Sandeep', 'Behera')
print(emp_1.__dict__)


emp_1.fullname = "Alex Smith"
print(emp_1.__dict__)

emp_1.age = 20
print(emp_1.__dict__)

运行上面,结果是:

{'f_name': 'Sandeep', 'l_name': 'Behera', 'email': 'Sandeep.Behera@hotmail.com'}
{'f_name': 'Alex', 'l_name': 'Smith', 'email': 'Alex.Smith@hotmail.com'}
{'f_name': 'Alex', 'l_name': 'Smith', 'email': 'Alex.Smith@hotmail.com', 'age': 20}

为什么即使在我分配时“全名”也没有出现在字典中

emp_1.fullname = "Alex Smith"

但它显示“年龄”属性。它必须与装饰器做些什么吗?提前致谢。

回答

您修饰的 setter 不会创建属性fullname。如下向您的 setter 添加新行将为您提供一个属性full_name

@fullname.setter
def fullname(self, name):
    first, last = name.split(' ')
    self.f_name = first
    self.l_name = last
    self.email = self.f_name + '.' + self.l_name + '@hotmail.com'
    self.full_name = name      # creating an attribute full_name

结果如下:

{'f_name': 'Sandeep', 'l_name': 'Behera', 'email': 'Sandeep.Behera@hotmail.com'}
{'f_name': 'Alex', 'l_name': 'Smith', 'email': 'Alex.Smith@hotmail.com', 'full_name': 'Alex Smith'}
{'f_name': 'Alex', 'l_name': 'Smith', 'email': 'Alex.Smith@hotmail.com', 'full_name': 'Alex Smith', 'age': 20}


以上是__dict__对于未显示@property属性的对象的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>