Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python __lt__() Magic Method

#1
Python __lt__() Magic Method

Short summary:

  • To customize the behavior of the less than operator x < y, override the __lt__() dunder method in your class definition.
  • Python internally calls x.__lt__(y) to obtain a return value when comparing two objects using x < y.
  • The return value can be any data type because any value can automatically converted to a Boolean by using the bool() built-in function.
  • If the __lt__() method is not defined, Python will raise a TypeError.

Syntax


__lt__(self, other)

To use the less than operator on custom objects, define the __lt__() “dunder” magic method that takes two arguments: self and other. You can then use attributes of the custom objects to determine if one is less than the other.

The method should return a Boolean True or False — however, this is not required because every object can be automatically converted to a Boolean value using the built-in bool() function.

Let’s have a look at an example next.

Example


In the following code, you compare two persons with each other by using the age attribute as a decision criterion:

class Person: def __init__(self, age): self.age = age def __lt__(self, other): return self.age < other.age alice = Person(18)
bob = Person(17)
carl = Person(18) print(alice < bob)
# False print(alice < carl)
# False print(bob < alice)
# True

For example, because Alice’s age is 18 years and Bob’s 17 years, the expression alice < bob evaluates to True.

Background Video





Default Implementation of __lt__


The __lt__() dunder method doesn’t have a default implementation. If you try to compare objects using the less than operator <, Python will simply raise a TypeError.

class Person: def __init__(self, age): self.age = age alice = Person(18)
bob = Person(17)
carl = Person(18) print(alice < bob)
Traceback (most recent call last): File "C:\Users\...\code.py", line 10, in <module> print(alice < bob)
TypeError: '<' not supported between instances of 'Person' and 'Person'

TypeError: ‘<‘ not supported between instances of ‘…’ and ‘…’


If you get the TypeError: '<' not supported between instances of '...' and '...', you try to compare two objects using the less than operator x < y for which the __lt__() magic method is not defined.

class Finxter: pass x = Finxter()
y = Finxter() x < y # Python will raise an error!

Output:

Traceback (most recent call last): File "C:\Users\...\code.py", line 8, in <module> x < y # Python will raise an error!
TypeError: '<' not supported between instances of 'Finxter' and 'Finxter'

To fix the error, simply define the __lt__(self, other) method in your class definition and return any object that will then be converted to a Boolean True or False.

class Finxter: def __lt__(self, other): return 42 x = Finxter()
y = Finxter() x < y # Now it works!
# 42

Commutativity of Less Than <


The output of x < y and y < x may be different because the former calls x.__lt__(y) and the latter calls y.__lt__(x). If x and y have different definitions of the dunder method __lt__(), the operation becomes non-commutative.

You can see this in the following example:

class Person: def __lt__(self, other): return False class Human: def __lt__(self, other): return True alice = Person()
bob = Human() print(alice < bob)
# False print(bob < alice)
# True


https://www.sickgaming.net/blog/2021/11/...ic-method/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

[-]
Discord

[-]
Active Threads
News - Stardew Valley’s Latest 1.5.5 Upd...
Last Post: xSicKxBot
Today 07:10 AM
» Replies: 0
» Views: 1
News - Hood: Outlaws & Legends Season 2 ...
Last Post: xSicKxBot
Today 07:09 AM
» Replies: 0
» Views: 0
(Indie Deal) RE8, Frontier, Slitherine, ...
Last Post: xSicKxBot
Today 05:00 AM
» Replies: 0
» Views: 6
Microsoft - Inclusion for all this Inter...
Last Post: xSicKxBot
Today 02:39 AM
» Replies: 0
» Views: 5
News - .hack//G.U. Last Recode Is Coming...
Last Post: xSicKxBot
Today 02:39 AM
» Replies: 0
» Views: 3
News - A New Peacemaker TV Show Trailer ...
Last Post: xSicKxBot
Today 02:39 AM
» Replies: 0
» Views: 3
(Indie Deal) 2K, SNK, Ziggurat & Graffit...
Last Post: xSicKxBot
Yesterday 11:12 PM
» Replies: 0
» Views: 11
News - George Clooney Reveals Why He Tur...
Last Post: xSicKxBot
Yesterday 08:39 PM
» Replies: 0
» Views: 9
(Indie Deal) 2K, SNK, Ziggurat & Graffit...
Last Post: xSicKxBot
Yesterday 05:39 PM
» Replies: 0
» Views: 10
Microsoft - Fund manager RFP opens for M...
Last Post: xSicKxBot
Yesterday 05:39 PM
» Replies: 0
» Views: 3

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com



Discord Server © SickGaming.net 2012-2021