Last active
March 5, 2019 12:51
-
-
Save kateolenya/a3a39a76e55180144fa4f8032dd80aec to your computer and use it in GitHub Desktop.
Encapsulation with magic methods in Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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