Python class decorator

I am trying to decorate the actual class using this code:

def my_decorator(cls):
    def wrap(*args, **kw):
        return object.__new__(cls)
    return wrap

@my_decorator
class TestClass(object):
    def __init__(self):
        print "__init__ should run if object.__new__ correctly returns an instance of cls"


test = TestClass() # shouldn't TestClass.__init__() be run here?

I have no errors, but I also do not see the message from TestClass.__init__().

According to the docs for the new style classes :

Typical implementations create a new instance of the class by calling the supcllasss method __new__(), using super(currentclass, cls).__new__(cls[, ...])with the appropriate arguments, and then, if necessary, modifying the newly created instance before returning it.

If the __new__()cls instance returns, then the new instance __init__()will be called as __init__(self[, ...]), where self is the new instance, and the rest of the arguments are the same as for __new__().

Any ideas why __init__not working?

, __new__ :

return super(cls.__bases__[0], cls).__new__(cls)

TypeError:

TypeError: super.__new__(TestClass): TestClass is not a subtype of super
+3
2

__init__ , object.__new__ , . cls.__call__(*args, **kwargs), , cls(*args, **kwargs), . , : . __new__ , . __new__, __init__, , __call__.

, , super __new__ . , , .

+11

, __init__

def my_decorator(cls):
    print "In my_decorator()"
    def wrap(*args, **kw):
        print "In wrap()"
        return cls.__init__(object.__new__(cls), *args, **kw)
    return wrap

@my_decorator
class TestClass(object):
    def __init__(self):
        print "__init__ should run if object.__new__ correctly returns an instance of cls"
0

Source: https://habr.com/ru/post/1770639/


All Articles