0

Is there a way to know the class to which one method belongs. In the following code I would like to build one decorator that could call either the method named get_f_name or set_f_name if the function f has none argument or not. The idea is to build one decorator imitating the getter-setter syntax of jQuery.

To do that, I must know from which class the function f comes.

def jqueryize(f):
#    ????

class Test():
    def __init__(self):
        self.string      = "A little text..."
        self.dictionnary = {
            'key_1': 12345,
            'key_2': [1, 2, 3, 4, 5]
        }
        self.boolean = True

    @jqueryize
    def data(
        self,
        string      = None,
        dictionnary = None,
        boolean     = None
    ):
        ...

    def set_data(
        self,
        string,
        dictionnary,
        boolean
    ):
        ...

    def get_data(self):
        print(
            self.string,
            self.dictionnary,
            self.boolean,
            sep = "\n"
        )
  • 1
    This question is little bit difficult to understand. Could you e.g. clarify it with an example how you would like it to work. If you are looking magical set, get functions I suggest you take a look Python properties http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters – Mikko Ohtamaa Mar 16 '13 at 13:27

1 Answers1

0

At the time jqueryize runs, the Test class doesn't exist, and data is just a normal function. One way to do what you want would be with two decorators - one for the method, which just marks the method to be jqueryized by setting an attribute on the function, and then a class decorator that finds all of the marked methods in the class and does the actual transformation. The thing that makes this work is the fact that the class decorator executes after the class is created.

You could also achieve the same result using a metaclass. This is more fiddly to implement, but you could avoid having to decorate every class that has decorated methods, as long as they subclassed an instance of the metaclass that does the heavy lifting.

babbageclunk
  • 8,523
  • 1
  • 33
  • 37