Update A List Every Time A Function Within A Class Is Executexecuted With The Function Arguments And Values
In the last 6 months, I have created many classes and function for different calculations. Now I would like to join them into a class so it could be used by other users. Like many
Solution 1:
Here's how to use a decorator, per Moinuddin Quadri's suggestion:
defremember(func):
definner(*args, **kwargs):
args[0].procedure.append({'method': func,
'args': args,
'kwargs': kwargs})
return func(*args, **kwargs)
return inner
classprocess(object):def__init__(self):
self.procedure = []
@rememberdefMethodA(self, valueA):
pass
@rememberdefMethodB(self, valueB):
pass
This makes it so that every time each of these decorated methods is called, it will append their arguments to that object's procedure array. This decorator will fail on non-class methods.
Calling these commands:
p = process()
p.MethodA(1)
p.MethodB(2)
p.MethodA(3)
p.MethodB(4)
print p.procedure
will result in the following if pretty printed:
[{'args': (<__main__.process object at 0x7f25803d28d0>, 1),
'kwargs': {},
'method': <functionMethodAat 0x7f25803d4758>},
{'args': (<__main__.process object at 0x7f25803d28d0>, 2),
'kwargs': {},
'method': <functionMethodBat 0x7f25803d4848>},
{'args': (<__main__.process object at 0x7f25803d28d0>, 3),
'kwargs': {},
'method': <functionMethodAat 0x7f25803d4758>},
{'args': (<__main__.process object at 0x7f25803d28d0>, 4),
'kwargs': {},
'method': <functionMethodBat 0x7f25803d4848>}]
where <__main__.process object at 0x7f25803d28d0>
is the process object (self
)
Read more about decorators here: https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Decorators
Post a Comment for "Update A List Every Time A Function Within A Class Is Executexecuted With The Function Arguments And Values"