Skip to content

Instantly share code, notes, and snippets.

@Mause
Last active August 29, 2015 13:56
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 Mause/8884395 to your computer and use it in GitHub Desktop.
Save Mause/8884395 to your computer and use it in GitHub Desktop.
simple example of type specialisation with Python
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