无论何时使用实例,控制流动叉; 一种类型的对象沿着一条代码路径向下移动,而其他类型的对象沿着另一条对象向下移动 - 即使它们实现了相同的接口!
并暗示这是一件坏事.
但是,我之前使用过这样的代码,我认为这是一种OO方式.类似于以下内容:
class MyTime(object):
def __init__(self, h=0, m=0, s=0):
self.h = 0
self.m = 0
self.s = 0
def __iadd__(self, other):
if isinstance(other, MyTime):
self.h += other.h
self.m += other.m
self.s += other.s
elif isinstance(other, int):
self.h += other/3600
other %= 3600
self.m += other/60
other %= 60
self.s += other
else:
raise TypeError('Addition not supported for ' + type(other).__name__)
Run Code Online (Sandbox Code Playgroud)
所以我的问题:
这是isinstance
"pythonic"和"好"OOP的用法吗?
不一般.对象的接口应该定义它的行为.在上面的示例中,如果other
使用一致的接口会更好:
def __iadd__(self, other):
self.h += other.h
self.m += other.m
self.s += other.s
Run Code Online (Sandbox Code Playgroud)
即使这看起来功能较少,但在概念上它更清洁.现在,如果other
与接口不匹配,则将其保留为语言以引发异常.您可以int
通过 - 例如 - MyTime
使用整数的"接口" 创建"构造函数"来解决添加时间的问题.这样可以使代码更清晰,并为下一个人留下更少的惊喜.
其他人可能不同意,但我觉得isinstance
如果你在特殊情况下使用反射,例如在实现插件架构时,可能会有一个地方.