Last active
August 29, 2015 13:56
-
-
Save Mause/8884395 to your computer and use it in GitHub Desktop.
simple example of type specialisation with Python
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
from functools import wraps | |
def specific_magic(f): | |
@wraps(f) | |
def wrapper(self, *args, **kwargs): | |
for arg in args: | |
if type(arg) != self.__class__: | |
raise TypeError('{} not of type {}'.format( | |
arg, self.__class__.__name__ | |
)) | |
return f(self, *args, **kwargs) | |
return wrapper | |
class FruitBox(object): | |
def __init__(self, num=0): | |
self.num = num | |
@specific_magic | |
def __add__(self, other): | |
self.num += other.num | |
return self | |
def __repr__(self): | |
return "{} {}'s".format(self.num, self.__class__.__name__) | |
class AppleBox(FruitBox): | |
pass | |
class OrangeBox(FruitBox): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment