【发布时间】:2010-06-24 15:50:25
【问题描述】:
this 问题的副作用是我被引导到this post,它指出:
每当使用 isinstance 时,控制流分叉;一种类型的对象在一个代码路径下,而其他类型的对象在另一个上——即使它们实现了相同的接口!
并暗示这是一件坏事。
但是,我以前使用过这样的代码,我认为这是一种面向对象的方式。类似于以下内容:
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__)
所以我的问题:
这是isinstance "pythonic" 和 "good" OOP 的用法吗?
【问题讨论】: