为什么self.email和self._email总是在@property下面的python类中彼此相等?

问题描述 投票:0回答:1

我从这个博客中得到了一个关于@property用法的例子:https://tomayko.com/blog/2005/getters-setters-fuxors。运行下面的文章代码后,我注意到self.email和self._email是平等的,不知道为什么?

class Contact(object):
    def __init__(self, first_name=None, last_name=None,
                 display_name=None, email=None):
        self.first_name = first_name
        self.last_name = last_name
        self.display_name = display_name
        self.email = email  #1 here the variable name is "email"

    def print_info(self):
        print self.display_name, "<" + self.email + ">"

    def set_email(self, value):
        if '@' not in value:
            raise Exception("This doesn't look like an email address.")
        self._email = value #2 here the name is "_email" with a leading underscore

    def get_email(self):
        return self._email #3 here with a leading underscore too

    email = property(get_email, set_email) #4 the name is "email" without underscore
C = Contact('a','b','c','[email protected]')
print C.email
C.email = 'e@emailcom'
print C.email

通过逐步执行代码,我注意到这两个变量总是相同的。这怎么发生的?我想知道它背后的功能是什么并支持它。

python properties underscore.js
1个回答
0
投票

我不知道你想要做什么,但变量_setemail被提到两次,但它们都没有提到你的输出。还要查看可能有助于您了解程序优先级的LEGB规则。

© www.soinside.com 2019 - 2024. All rights reserved.