我有一个命名元组类型的这个子类:
class User(namedtuple('User', ['first_name'])):
__slots__ = ()
def __new__(cls, *args, **kwargs):
result = super().__new__(cls, *args, **kwargs)
if not result.first_name:
raise InvalidUserError({InvalidUserError.EMPTY_FIRST_NAME})
return result
创建新用户按预期工作:
>>> try: User(first_name='')
... except Exception as e: print(type(e))
<class 'InvalidUserError'>
但是,当_replace
使用时,__new__
不会调用该方法:
>>> User(first_name='foo')._replace(first_name='')
User(first_name='')
有没有办法保证不变量namedtuple
?我正在使用 Python 3.4。