Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Challenge: Singleton Logger | Metaclasses in Real-World Scenarios
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Python Metaclasses Demystified

bookChallenge: 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.

Tehtävä

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.

Ratkaisu

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 4
single

single

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Suggested prompts:

Can you show me an example of how to implement a singleton using a metaclass?

What are some other use cases for metaclasses besides singletons?

How does customizing the __call__ method in a metaclass work?

close

bookChallenge: Singleton Logger

Pyyhkäise näyttääksesi valikon

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.

Tehtävä

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.

Ratkaisu

Switch to desktopVaihda työpöytään todellista harjoitusta vartenJatka siitä, missä olet käyttämällä jotakin alla olevista vaihtoehdoista
Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 4
single

single

some-alt