I have a specific class, which is quite general, and I want to derive another class, where the a command is run before the class methods.
The path I chosen to follow is based on https://stackoverflow.com/a/55035043/1424118 . I tried many other, but I felt that I understand how it works. Well, here was I wrong as well. My understanding was that the process is as follows: 1) create a subclass, 2) get all callable methods of the base class, 3) overwrite these methods with their decorated version.
My code is:
from functools import wraps, partial
def deco_func(func): #, channel):
@wraps(func)
def new_function(*args,**kwargs):
print("Decorator func.")
return func(*args,**kwargs)
return new_function
print("checking the operation of the decorator function")
def sq(a):
print(a**2)
sq2 = deco_func(sq)
sq(1.1)
sq2(1.3) # yep, sq2 works
class my_class():
def __init__(self, a):
self.a = a
def square(self):
self.a = self.a**2
print(self.a)
class my_subclass(my_class):
def __init__(self, func, *args, **kwargs):
super().__init__(*args, **kwargs)
# go over all elements in my_class and if it is callable, apply the
# decorator function
for attr_name in my_class.__dict__:
attr = getattr(self, attr_name)
if callable(attr) and a:
print("Callable method found: %r" % attr_name)
setattr(self, attr_name, partial(func, attr))
class my_subclass2(my_class):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# go over all elements in my_class and if it is callable, apply the
# decorator function
for attr_name in my_class.__dict__:
attr = getattr(self, attr_name)
if callable(attr) and a:
print("Callable method found: %r" % attr_name)
setattr(self, attr_name, partial(deco_func, attr))
print("\nOriginal class:")
a = my_class(1.05)
a.square()
a.square()
print("Supposed to be 1.05^4: %r" % a.a)
print("\nFirst subclass version:")
b = my_subclass(a=1.07, func=deco_func)
b.square()
b.square()
print("Supposed to be 1.07^4: %r" % b.a)
print("\nSecond subclass version:")
c = my_subclass2(a=1.03)
c.square()
c.square()
print("Supposed to be 1.03^4: %r" % c.a)
The output is:
checking the operation of the decorator function
1.2100000000000002
Decorator func.
1.6900000000000002
Original class:
1.1025
1.21550625
Supposed to be 1.05^4: 1.21550625
First subclass version:
Callable method found: '__init__'
Callable method found: 'square'
Supposed to be 1.07^4: 1.07
Second subclass version:
Callable method found: '__init__'
Callable method found: 'square'
Supposed to be 1.03^4: 1.03
The issue is that b.square()
and c.square()
return a function object, but I do not see why. I expect c.square() to be the same as deco_func(my_class.square()), which is sq2(). The obvious questions are where am I wrong, why did the decorated class function return another function, and how could I overcome this problem?
I use python 3.6.9.