前几天我正在搞乱一些(坦率无用的)python代码试图创建一个像bool
子类一样的先前不可归类的类,这是我所得到的:
def make_subclassable(old_cls):
"""
Make a class that was previously unavailable for subclassing now subclassable.
Examples of unsubclassable classes are 'bool', 'EllipsisType', and 'NotImplementedType'.
"""
class _faketype(ABCMeta):
@classmethod
def __instancecheck__(cls, instance):
return isinstance(instance, (new_cls, old_cls))
new_cls = _faketype('Subclassable' + old_cls.__name__.title(), \
old_cls.__mro__[1:], # don't include the class itself
dict(old_cls.__dict__)
)
return new_cls
问题与新类'__repr__
方法有关。例如:
>>> SubclassableBool = make_subclassable(bool)
>>> repr(SubclassableBool()) # should display 'False'
'<SubclassableBool object at 0x028C9210>'
当我使用_faketype
创建新类时,旧类中的整个类dict将被复制到新类中,除了__repr__
之外,其他所有类似乎都有效。我有没有办法让旧的__repr__
进入新班级?
注意:解决方案可能是hackish,因为我对这是否可行而不是一个干净的解决方案更感兴趣,但是如果它们是纯Python的话会很好。