Q. Do you want to implement a method chain easily?
A. Yes.
class MyList(list):
...
def method(defined_type):
def wrap(f):
def wrapper(*args, **kwargs):
return defined_type(f(*args, **kwargs))
return wrapper
def decorator(f):
setattr(defined_type, f.__name__, wrap(f))
return decorator
@method(MyList)
def map(l, func):
return [func(el) for el in l]
print(MyList([1, 2, 3]).map(lambda x: x+1).map(lambda x: x+2)) # [4, 5, 6]
Recommended Posts