Ali SH Ali SH - 2 months ago 6
Python Question

passing function to a class using @property.setter decorator

I am making a class that i want to declare a variable which hold a function in it and i want to call them after i do some processing on some information.but i don't know how to use property decorator in this situation.
i already have this code:

class MyClass:
def __init__(self):
self.callback = None
def run():
#do something here...
result = self.callback(result)
print(result)

def func1(result):
result = result ** 2
return result

def func2(result):
result = result ** 4
return result


class1 = MyClass()
class1.callback = func1
class1.run()
class1.callback = func2
class1.run()


my question is how i can use
@property
and
@property.setter
and
@property.getter
decorator for self.callback in this code?

Answer

I based on this code don't see a need for properties but here it is anyway.

class MyClass:
    def __init__(self):
        self.__callback = None

    @property
    def cb(self):
        return self.__callback

    @cb.setter
    def cb(self, new_cb):
        self.__callback = new_cb
Comments