Is this use of isinstance pythonic/“good”?

前端 未结 4 1832
囚心锁ツ
囚心锁ツ 2021-02-02 01:41

A side effect of this question is that I was lead to this post, which states:

Whenever isinstance is used, control flow forks; one type of object goes dow

4条回答
  •  一生所求
    2021-02-02 02:07

    Not in general. An object's interface should define its behavior. In your example above, it would be better if other used a consistent interface:

    def __iadd__(self, other):
        self.h += other.h
        self.m += other.m
        self.s += other.s
    

    Even though this looks like it is less functional, conceptually it is much cleaner. Now you leave it to the language to throw an exception if other does not match the interface. You can solve the problem of adding int times by - for example - creating a MyTime "constructor" using the integer's "interface". This keeps the code cleaner and leaves fewer surprises for the next guy.

    Others may disagree, but I feel there may be a place for isinstance if you are using reflection in special cases such as when implementing a plugin architecture.

提交回复
热议问题