【发布时间】:2010-05-19 16:24:41
【问题描述】:
我有一些依赖于类型检查的 Python 代码。我会尝试用数学语言表达我的问题,这样就很清楚了。我有几个类相互对应,形成一个继承链。
class Real(object):
pass
class Integer(Real):
pass
class Natural(Integer):
pass
我有一个包含类型的元组。其中每一个都对应于某个函数的域。
t1 = ( Real, Real )
t2 = ( Real , Integer )
我想做某种形式的类型检查,如果元组中的每个坐标都是指定域的子类,则给定另一个元组( Natural , Natural )。例如对于某些功能getcompatibles 我想拥有:
getcompatibles( ( Real, Real ) ) = [ t1 ]
getcompatibles( ( Real, Integer ) ) = [ t1, t2 ]
getcompatibles( ( Natural, Natural ) ) = [ t1, t2 ]
getcompatibles( ( Natural, Real ) ) = [ t1 ]
我能想到的唯一解决方案是遍历每个 for domain (t1, t2) 遍历 __subclasses__ 中的每个类型,并检查 isinstance 对于给定输入是否为 True。
虽然效率极低,是否有更 Pythonic 的方式来做到这一点?
【问题讨论】:
-
更改了 is_compatible -> getcompatibles
标签: python oop inheritance