# EmailField

# 检查用户邮箱是否合法

class User:

    email = EmailField(attrname='_email')

    def __init__(self, name, email):
        self.name = name
        self.email = email

    def __repr__(self):
        return "User(name='{}', email='{}')".format(self.name, self.email)


class EmailField:

    EMAIL_MOD = re.compile('^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$')

    def __init__(self, attrname):
        self.attrname = attrname

    def __get__(self, instance, owner):
        return getattr(instance, self.attrname)

    def __set__(self, instance, value):
        if not self.EMAIL_MOD.match(value):
            raise Exception('{} is not a valid email'.format(value))

        setattr(instance, self.attrname, value)

    def __delete__(self, instance):
        raise Exception('can not delete email')

>>> user
User(name='fasionchan', email='admin@fasionchan.com')
>>> user.email
'admin@fasionchan.com'
>>> user.email = 'not an email'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in __set__
Exception: not an email is not a valid email
>>> user.__dict__
{'name': 'fasionchan', '_email': 'admin@fasionchan.com'}