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.
Løsning
Tak for dine kommentarer!
single
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Fantastisk!
Completion rate forbedret til 4.76
Challenge: Singleton Logger
Stryg for at vise menuen
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.
Løsning
Tak for dine kommentarer!
single