[Python] Wrap class method with argument(s) only once

Discussão em 'Python' iniciado por Stack, Maio 15, 2025.

  1. Stack

    Stack Membro Participativo

    There are two classes and I want to wrap item.foo method only once, to prevent cache = {param1: 'param_value'} being reinited

    class Foo:
    _count = 0

    def foo(self, param2):
    self._count += param2


    class Bar:
    _collection = [Foo(), Foo(), Foo()]

    def bar(self, param1, param2):
    for item in self._collection:
    wrapped_function = wrapper(item.foo, param1)
    wrapped_function(param2)


    def wrapper(func, param1):
    # some database call or whatever
    cache = {param1: 'param_value'}

    def _wrapper(*args, **kwargs):
    # access value to read
    print(cache[param1])
    return func(*args, **kwargs)
    return _wrapper


    bar = Bar()
    bar.bar(1, 2)


    It can be achieved if wrapper had no params in it and was used as a simple decorator, but I have to pass a param1 in it, though it's always the same. I also can save cache = {param1: 'param_value'} before the cycle in def bar and pass it as the parameter, but I was wondering if there any other way to accomplish it.

    Kinda can't wrap my head around it(pun intended)

    Continue reading...

Compartilhe esta Página