简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM