为了完整起见,这是另一个答案,它显示了如何使用元类以编程方式将整数具有的所有算术方法添加到自定义类中。请注意,尚不清楚在每种情况下返回与操作数具有相同边界的 BoundedInt 是否有意义。该代码还与 Python 2 和 3 兼容。
class MetaBoundedInt(type):
# int arithmetic methods that return an int
_specials = ('abs add and div floordiv invert lshift mod mul neg or pos '
'pow radd rand rdiv rfloordiv rlshift rmod rmul ror rpow '
'rrshift rshift rsub rtruediv rxor sub truediv xor').split()
_ops = set('__%s__' % name for name in _specials)
def __new__(cls, name, bases, attrs):
classobj = type.__new__(cls, name, bases, attrs)
# create wrappers for specified arithmetic operations
for name, meth in ((n, m) for n, m in vars(int).items() if n in cls._ops):
setattr(classobj, name, cls._WrappedMethod(cls, meth))
return classobj
class _WrappedMethod(object):
def __init__(self, cls, func):
self.cls, self.func = cls, func
def __get__(self, obj, cls=None):
def wrapper(*args, **kwargs):
# convert result of calling self.func() to cls instance
return cls(self.func(obj, *args, **kwargs), bounds=obj._bounds)
for attr in '__module__', '__name__', '__doc__':
setattr(wrapper, attr, getattr(self.func, attr, None))
return wrapper
def with_metaclass(meta, *bases):
""" Py 2 & 3 compatible way to specifiy a metaclass. """
return meta("NewBase", bases, {})
class BoundedInt(with_metaclass(MetaBoundedInt, int)):
def __new__(cls, *args, **kwargs):
lower, upper = bounds = kwargs.pop('bounds')
val = int.__new__(cls, *args, **kwargs) # supports all int() args
val = super(BoundedInt, cls).__new__(cls, min(max(lower, val), upper))
val._bounds = bounds
return val
if __name__ == '__main__':
# all results should be BoundInt instances with values within bounds
v = BoundedInt('64', 16, bounds=(0, 100)) # 0x64 == 100
print('type(v)={}, value={}, bounds={}'.format(type(v).__name__, v, v._bounds))
v += 10
print('type(v)={}, value={}, bounds={}'.format(type(v).__name__, v, v._bounds))
w = v + 10
print('type(w)={}, value={}, bounds={}'.format(type(w).__name__, w, w._bounds))
x = v - 110
print('type(x)={}, value={}, bounds={}'.format(type(x).__name__, x, x._bounds))
输出:
type(v)=BoundedInt, value=100, bounds=(0, 100)
type(v)=BoundedInt, value=100, bounds=(0, 100)
type(w)=BoundedInt, value=100, bounds=(0, 100)
type(x)=BoundedInt, value=0, bounds=(0, 100)