1
    def createtime(cls):
        def wrapper(*args, **kwargs):
            instance = cls(*args, **kwargs)
            print('Creatime is', datetime.now())
            return instance
        return wrapper

@creatime
class A:
  pass

@creatime 
class B(A):
  pass

I skip all imports and classes code. It raises exeption: TypeError: function() argument 'code' must be code, not str. How to resolve it?

Viking099
  • 11
  • 1
  • What's the full error? See how to create a [mcve] and [edit] the question. – Peter Wood Jul 23 '22 at 13:18
  • Please correct the indentation and spelling errors of your post. – quamrana Jul 23 '22 at 13:26
  • Do the answers to this [question](https://stackoverflow.com/questions/681953/how-to-decorate-a-class) help at all? – quamrana Jul 23 '22 at 13:27
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jul 23 '22 at 14:39

1 Answers1

0

Similarly to the decorations of functions, to decorate a class

@deco
class A:
    ...

is a shortcut of (some say syntactic sugar, I don't like the term):

class A:
    ...
A = deco(A)

And this usage makes sense if the decorator takes the original class and returns a modified class or sometimes even the original class (for instance if the decorator just adds the class to some registry).

In the code you have posted (ignoring typos and formatting), the createtime function takes a class, but returns a function. A in your code is function, not a class.

In the next step you are trying to subclass that function to create the class B and that is an error. A base class must be a class, obviously. Unfortunately the confusing error message makes that not clear.

How to do it correctly depends on what you want to achieve and that is not clear. Maybe you wanted just to decorate the __init__ or the __new__ method to print the timestamp of its invocation. A class decorator could do just that as well. Just a note that if you would do that for the base class A, it will be inherited by B. If you decorate both, the timestamp will be printed twice.

VPfB
  • 14,927
  • 6
  • 41
  • 75