Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Encapsulation with magic methods in Python 3
#!/usr/bin/python3
class Phone:
def __init__(self, number): # magic method / inititalizer
print( "The Phone object was created" )
self.number = number
def __lt__(self, other): # magic method / rich comparison
return self.number < other.number
my_phone = Phone(20)
other_phone = Phone(30)
if my_phone < other_phone:
print( "Two instances of custom class were compared" )
print( "'__lt__' was called implicitly" )
if my_phone.__lt__(other_phone):
print( "Now, '__lt__' was used explicitly" )
input( "Press Enter to exit" )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.