Skip to content

Instantly share code, notes, and snippets.

@kateolenya
Last active March 5, 2019 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kateolenya/a3a39a76e55180144fa4f8032dd80aec to your computer and use it in GitHub Desktop.
Save kateolenya/a3a39a76e55180144fa4f8032dd80aec to your computer and use it in GitHub Desktop.
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