How to add decorator to dynamically create class

I want to convert this code to be dynamic:

@external_decorator
class Robot:
    counter = 0

    def __init__(self, name):
        self.name = name

    def sayHello(self):
        return "Hi, I am " + self.name

I can create the class dynamically, this way:

def Rob_init(self, name):
    self.name = name

Robot2 = type("Robot2", 
              (), 
              {"counter":0, 
               "__init__": Rob_init,
               "sayHello": lambda self: "Hi, I am " + self.name})

however i dont know how to add the decorator @external_decorator.

Thks

>Solution :

@decorator is just syntactic sugar for i = decorator(i). So:

Robot2 = external_decorator(type("Robot2", ...))

Leave a Reply