decorator - What is the practical use of class decorations in Python? -


in python 2.6, pep 3129 introduced "class decorators" python compliment function decorators present in language. cannot see when or might used practically, , interested in knowing if there improvement in performance using class decorators on not using them achieve same result.

class decorators function take class objects input , change object binds name of input class output of function (usually want return same class). alternative inheritance , metaclasses customize class behavior , different in act after class has been created, instead of affecting class creation process. difference class decorators not inherited advantageous on metaclasses in situations.

def register_handlers(cls):     token = 'handle_'     cls.handler_dict = {k[len(token):] : getattr(cls,k) k in dir(cls) if k.startswith(token)}     return cls  @register_handlers class handler:     def handle_input(self):         pass      def handle_output(self):         pass      def handle_error(self):         pass 

additionally not required class decorator modifies class @ all, return , e.g. register somewhere:

game_objects = {}  def register_object(cls):     game_objects[cls.__name__] = cls     return cls  @register_object class chair:     pass  @register_object class car:     pass 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -