1

Is there a way to test whether a costume class had explicitly defined an attribute like __gt__? To put things in context consider these two classes:

class myclass1:
    def __init__(self, val):
        self.val = val

    def __gt__(self, other):
        if type(other) is int:
            return self.val > other
        else:
            return self.val > other.val


class myclass2:
    def __init__(self, val):
        self.val = val

Since I've defined an inequality attribute only for myclass1 and not for myclass2 calling

x1 = myclass1(5); x2 = myclass2(2)
x1 > x2
x2 < x1

will use myclass1.__gt__ in both cases. Had I defined myclass2.__lt__, the last line would have invoked it. But I didn't. So x1's __gt__ takes hold in both calls. I think I understand this (but comments are welcomed).

So my question: Is there a way to know which inequalities had been explicitly defined for a custom class? Because

hasattr(x2, '__gt__')

returns True anyway.

Aguy
  • 7,851
  • 5
  • 31
  • 58

1 Answers1

2

You can check inside the __dict__ for each class:

'__gt__' in x2.__class__.__dict__
Out[23]: False

'__gt__' in x1.__class__.__dict__
Out[24]: True

Or, using built-ins in order to not rely on dunders:

'__gt__' in vars(type(x1))
Out[31]: True

'__gt__' in vars(type(x2))
Out[32]: False
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • Note that this will fail to detect the case where a class inherits a `__gt__` from a superclass (rather than defining it itself). It's unclear whether this would count as "explicit" according to the question. – BrenBarn Jul 30 '16 at 07:01
  • 1
    What if `__gt__` is not defined in the class itself but it is being inherited from a parent class? I would recommend comparing: `type(x2).__gt__` and `object.__gt__` – Ashwini Chaudhary Jul 30 '16 at 07:03
  • @AshwiniChaudhary - Great. Seems like an efficient way. – Aguy Jul 30 '16 at 11:30