我试图重载枚举子类的__init__()
方法。奇怪的是,普通类的模式不再适用于Enum。在
下面显示了使用普通类的所需模式:
class Integer:
def __init__(self, a):
"""Accepts only int"""
assert isinstance(a, int)
self.a = a
def __repr__(self):
return str(self.a)
class RobustInteger(Integer):
def __init__(self, a):
"""Accepts int or str"""
if isinstance(a, str):
super().__init__(int(a))
else:
super().__init__(a)
print(Integer(1))
# 1
print(RobustInteger(1))
# 1
print(RobustInteger('1'))
# 1
如果与枚举一起使用,则相同的模式将中断:
^{pr2}$
有一个更好的答案,但我还是把它贴出来,因为它可能有助于理解这个问题。
文件给出了以下提示:
所以我们必须等待重新定义
__new__
,直到类被创建。通过一些难看的修补,这通过了测试:必须重载
_missing_
钩子。WeekDay
的所有实例都是在首次定义类时创建的;WeekDay(date(...))
是索引操作,而不是创建操作,__new__
最初查找绑定到整数0到6的预先存在的值。否则,它将调用_missing_
,在这种情况下,您可以将date
对象转换为这样一个整数。在几个例子:
^{pr2}$(注意:
_missing_
在python3.6之前不可用。)在3.6之前,您似乎可以重写
EnumMeta.__call__
进行相同的检查,但我不确定这是否会产生意外的副作用。(关于__call__
的推理总是让我头晕目眩。)相关问题 更多 >
编程相关推荐