Is this use of isinstance pythonic/“good”?

前端 未结 4 1835
囚心锁ツ
囚心锁ツ 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 01:49

    To elaborate further on the comment I made under Justin's answer, I would keep his code for __iadd__ (i.e., so MyTime objects can only be added to other MyTime objects) and rewrite __init__ in this way:

    def __init__(self, **params):
        if params.get('sec'):
            t = params['sec']
            self.h = t/3600
            t %= 3600
            self.m = t/60
            t %= 60
            self.s = t
        elif params.get('time'):
            t = params['time']
            self.h = t.h
            self.m = t.m
            self.s = t.s
        else:
            if params:
                raise TypeError("__init__() got unexpected keyword argument '%s'" % params.keys()[0])
            else:
                raise TypeError("__init__() expected keyword argument 'sec' or 'time'")
    
    # example usage
    t1 = MyTime(sec=30)
    t2 = MyTime(sec=60)
    t2 += t1 
    t3 = MyTime(time=t1)
    

    I just tried to pick short keyword arguments, but you may want to get more descriptive than I did.

提交回复
热议问题