If duck-typing in Python, should you test isinstance?

前端 未结 3 1407
挽巷
挽巷 2021-02-04 05:01

You have a Python class which needs an equals test. Python should use duck-typing but is it (better/more accurate) to include or exclude an isinstance test in the eq

3条回答
  •  青春惊慌失措
    2021-02-04 05:45

    Using isintsance() is usually fine in __eq__() methods. You shouldn't return False immediately if the isinstance() check fails, though -- it is better to return NotImplemented to give other.__eq__() a chance of being executed:

    def __eq__(self, other):
        if isinstance(other, Trout):
            return self.x == other.x
        return NotImplemented
    

    This will become particularly important in class hierarchies where more than one class defines __eq__():

    class A(object):
        def __init__(self, x):
            self.x = x
        def __eq__(self, other):
            if isinstance(other, A):
                return self.x == other.x
            return NotImplemented
    class B(A):
        def __init__(self, x, y):
            A.__init__(self, x)
            self.y = y
        def __eq__(self, other):
            if isinstance(other, B):
                return self.x, self.y == other.x, other.y
            return NotImplemented
    

    If you would return False immediately, as you did in your original code, you would lose symmetry between A(3) == B(3, 4) and B(3, 4) == A(3).

提交回复
热议问题