-1

I stumpled into a problem of understanding the decorators. Compared to the code below, what is the use of the __lt__(self, number) method compared to the less_than(self, number) method? Is there any difference between the two methods and how they handle the arguments?

 class Sort:

    def __init__(self, number):
        self.number = number

    def __lt__(self, number):
        return self.number < number

    def less_than(self, number):
        return self.number < number
simonzack
  • 19,729
  • 13
  • 73
  • 118
  • 6
    This has nothing to do with decorators. `__lt__` is as special method Python will call when comparing two objects with `<`. – Martijn Pieters Sep 09 '14 at 09:57
  • possible duplicate of [Special (magic) methods in Python](http://stackoverflow.com/questions/1090620/special-magic-methods-in-python) – simonzack Sep 09 '14 at 10:22
  • This has nothing to do with decorators (which are something completely different). The rest of the question *is* pretty valid though. – WhyNotHugo Sep 09 '14 at 10:23

2 Answers2

2

The two functions, __lt__() and less_than() do the same thing. However, there is a big difference: When you use the "<" operator, the function __lt__ is called internally by python. So, you can do this

x = Sort(5)
y = Sort(10)
print(x < y)

The comparison x < y calls x.__lt__(y), and so it returns true. In this way you can change the behavior of built in operators for the specific class you have created. See "operator overloading" and "python magic methods" for more details

WhyNotHugo
  • 9,423
  • 6
  • 62
  • 70
blue_note
  • 27,712
  • 9
  • 72
  • 90
1

As Martijn Pieters said this has nothing to do with decorators.

s1 = Sort(1)
s2 = Sort(2)

if s1 < s2:
    print 'Yes'

if s1.less_than(2):
    print 'Yes'

See the difference? In the first if you compare to objects of type Sort. In the second if you invoke a method from instance s1 of type Sort.

gosom
  • 1,299
  • 3
  • 16
  • 35