Created
December 28, 2016 04:27
-
-
Save senorsmile/a17d16c19882ffc04e65fc026dc383c1 to your computer and use it in GitHub Desktop.
simplified custom type in python
This file contains hidden or 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/env python | |
| class MyType(object): | |
| def __init__(self, value): | |
| self.value = value | |
| def __add__(self, other): #overload '+' | |
| if not isinstance(other, MyType): #only works on MyType types | |
| return NotImplemented | |
| return self.__class__(self.value + other.value) | |
| def __str__(self): #overload print() | |
| return str(self.value) #well, not exactly. | |
| if __name__ == "__main__": | |
| obj = MyType(5) | |
| obj2 = MyType(6) | |
| obj3 = obj + obj2 | |
| print(obj3) #this should work just fine | |
| obj4 = obj3 + 7 | |
| print(obj4) #this should err out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment