0
MyClass = (decorator(params))(MyClass)

I don't understand what this code means, since a decorator would return a function then MyClass would become a function? That sounds weird, isn't MyClass supposed to stay a class?

EDIT:

def decorator(name, validate, doc=None):
    def dec(Class):
        privateName = "__" + name
        def getter(self):
            return getattr(self, privateName)
        def setter(self, value):
            validate(name, value)
            setattr(self, privateName, value)
        setattr(Class, name, property(getter, setter, doc=doc))
        return Class
    return dec
Almog
  • 452
  • 1
  • 7
  • 13
user14095422
  • 79
  • 1
  • 7
  • Does this answer your question? [How to decorate a class?](https://stackoverflow.com/questions/681953/how-to-decorate-a-class) – Samwise Aug 15 '20 at 20:11
  • You don't give the code that shows what the decorator does, so it's impossible to say what the actual result is. Typically a decorator you'd apply to a class would return a modified version of the class rather than some unrelated function. – Samwise Aug 15 '20 at 20:12
  • Your `decorator` function returns another function (`dec`) which takes a class as its argument, modifies the class, and returns it. The statement `decorator(params)(MyClass)` is basically the same as `dec(MyClass)`, with the values of `name` and `validate` bound within `dec` according to whatever `params` you passed in. – Samwise Aug 15 '20 at 20:19
  • @Samwise i just can't understand the syntax meaning of MyClass = decorator(params)(MyClass) – user14095422 Aug 15 '20 at 20:55
  • It's just two function calls. `decorator(params)` returns a function. `decorator(params)(MyClass)` calls that function with the argument `MyClass`. The way you'd use this as an actual decorator would be to just put `@decorator(params)` above your `class MyClass` statement -- it would have the same effect as the aforementioned sequence of function calls (because that's how decorators work; they're just syntactic sugar for "call this function, then use the resultant function to modify this other thing"). – Samwise Aug 16 '20 at 03:20

0 Answers0