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
Takk for tilbakemeldingene dine!
single
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Fantastisk!
Completion rate forbedret til 4.76
Challenge: Singleton Logger
Sveip for å vise menyen
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
Takk for tilbakemeldingene dine!
single