Challenge: Singleton Logger
You have seen how metaclasses can be used to implement the singleton pattern, ensuring that only a single instance of a class is ever created. This is especially useful for classes like loggers, where global state or resource management is important. By customizing the __call__ method in a metaclass, you can intercept object instantiation and control instance creation in a way that regular classes cannot.
Swipe to start coding
Implement a metaclass SingletonMeta so that the Logger class always returns the same instance, regardless of how many times it is instantiated. The Logger should store the name from the first instantiation and ignore subsequent names. The log method should return a string in the format "[name] message", where name is the logger's name and message is the argument passed to log.
Solução
Obrigado pelo seu feedback!
single
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Incrível!
Completion taxa melhorada para 4.76
Challenge: Singleton Logger
Deslize para mostrar o menu
You have seen how metaclasses can be used to implement the singleton pattern, ensuring that only a single instance of a class is ever created. This is especially useful for classes like loggers, where global state or resource management is important. By customizing the __call__ method in a metaclass, you can intercept object instantiation and control instance creation in a way that regular classes cannot.
Swipe to start coding
Implement a metaclass SingletonMeta so that the Logger class always returns the same instance, regardless of how many times it is instantiated. The Logger should store the name from the first instantiation and ignore subsequent names. The log method should return a string in the format "[name] message", where name is the logger's name and message is the argument passed to log.
Solução
Obrigado pelo seu feedback!
single