Answer the question
In order to leave comments, you need to log in
Python decorator, iterator, how to register a function?
The essence of the problem: there is a summator function (or, perhaps, any other with an arbitrary number of arguments). You need to wrap it in a decorator that will register it in the function list of the Caller object. Subsequently, you need to iterate and "execute" all registered functions.
I have difficulties, apparently an error in the decorator and in the app_func method (I want to register functions in the object), I need to somehow add the functions to the list and call them from __next. If you have any ideas, help, where to look?
class Caller:
def __init__(self, *args, **kwargs):
self.arg1 = args
self.arg2 = kwargs
self.list_func = []
self.count_list = 0
def __iter__(self):
return self
def __next__(self):
if len(self.list_func) > self.count_list:
res = self.list_func[self.count_list]
self.count_list += 1
return res
else:
raise StopIteration
def app_func(self, func):
self.list_func.append(func(*self.arg1, **self.arg2))
def register_function(caller0):
def my_decorator(func):
def wrapper(*args, **kwargs):
return caller0.app_func(func(*args, **kwargs))
return wrapper
return my_decorator
caller1 = Caller(1, 2, z=5) # создаем один объект Caller'а, который хранит в себе числовые аргументы
@register_function(caller1) # регистрируем функцию в обоих объектах
def summator(x, y, z): # сама функция просто возвращает сумму аргументов
return x + y + z
for result in caller1: # теперь будем лениво вызывать функции, зарегистрированные
print(result) # в caller1, выводя их результаты на экран
Answer the question
In order to leave comments, you need to log in
didn't fix your code much
class Caller:
def __init__(self, *args, **kwargs):
self.list_func = []
self.args = args
self.kwargs = kwargs
def __iter__(self):
for func in self.list_func:
yield f'{func.__name__}: {func(*self.args, **self.kwargs)}'
def app_func(self, func):
self.list_func.append(func)
def register_function(caller0):
def my_decorator(func):
caller0.app_func(func)
return my_decorator
caller1 = Caller(1, 2, z=5) # создаем один объект Caller'а, который хранит в себе числовые аргументы
@register_function(caller1) # регистрируем функцию в обоих объектах
def summator(x, y, z): # сама функция просто возвращает сумму аргументов
return x + y + z
@register_function(caller1) # регистрируем функцию в обоих объектах
def func_2(x, y, z): # сама функция просто возвращает сумму аргументов
return x * y * z
for result in caller1: # теперь будем лениво вызывать функции, зарегистрированные
print(result)
summator: 8
func_2: 10
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question