假设我有面向性能的类型mylib.color.Hardware
,它的用户友好型对应物mylib.color.RGB
和mylib.color.HSB
. 当用户友好的颜色传递到库函数时,它被转换为color.Hardware
. 现在它是通过检查传递的 arg 的类型来实现的。但是将来我想接受任何类型并自动转换,它提供了相应的转换功能。例如,实现“otherlib.color.LAB”的第三方库。
现在我正在玩原型,像这样:
class somelib:
class A(object):
def __init__(self, value):
assert isinstance(value, int)
self._value = value
def get(self):
return self._value
class userlib:
class B(object):
def __init__(self, value):
self._value = value
def __toA(self):
try: value = int(self._value)
except: value = 0
return somelib.A(value)
__typecasts__ = {somelib.A: __toA}
def autocast(obj, cast_type):
if isinstance(obj, cast_type): return obj
try: casts = getattr(obj, '__typecasts__')
except AttributeError: raise TypeError, 'type cast protocol not implemented at all in', obj
try: fn = casts[cast_type]
except KeyError: raise TypeError, 'type cast to {0} not implemented in {1}'.format(cast_type, obj)
return fn(obj)
def printValueOfA(a):
a = autocast(a, somelib.A)
print 'value of a is', a.get()
printValueOfA(userlib.B(42.42)) # value of a is 42
printValueOfA(userlib.B('derp')) # value of a is 0
这是我的第二个原型,不那么打扰但更冗长:
# typecast.py
_casts = dict()
def registerTypeCast(from_type, to_type, cast_fn = None):
if cast_fn is None:
cast_fn = to_type
key = (from_type, to_type)
global _casts
_casts[key] = cast_fn
def typeCast(obj, to_type):
if isinstance(obj, to_type): return obj
from_type = type(obj)
key = (from_type, to_type)
fn = _casts.get(key)
if (fn is None) or (fn is NotImplemented):
raise TypeError, "type cast from {0} to {1} not provided".format(from_type, to_type)
return fn(obj)
# test.py
from typecast import *
registerTypeCast(int, str)
v = typeCast(42, str)
print "result:", type(v), repr(v)
问题。是否存在具有相同功能的库?(我不想重新发明轮子,但我的 google-fu 没有产生任何结果。)或者可能是您可以建议更好(也许更 Pythonic)的方法?
编辑:添加了第二个原型。