Câu hỏi phỏng vấn Python
Câu hỏi

Is there a simple, elegant...

Câu trả lời

Yes, there are several simple and elegant ways to define singletons in Python, each with its own advantages and considerations. Here are some of the most commonly used methods:

1. Using a Metaclass

A metaclass can control the instantiation of a class. By overriding the __call__ method in the metaclass, you can ensure that only one instance of a class is created.

python Copy
class SingletonMeta(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]

class Singleton(metaclass=SingletonMeta):
    pass

This method is highly readable and reusable, and it's easy to test because you can mock the metaclass during testing[3][4].

2. Using a Decorator

A decorator can be used to wrap a class and control its instantiation. This approach is less intrusive and can be easily added or removed from a class.

python Copy
def singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance

@singleton
class Singleton:
    pass

This method is intuitive and additive, allowing for clear modifications without altering the class structure itself[4].

3. Using a Base Class

Implementing singleton behavior in a base class from which other singletons can inherit is another approach. This method uses the __new__ method to control instance creation.

python Copy
class SingletonBase:
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        re...
expert

expert

Gợi ý câu hỏi phỏng vấn

middle

Explain the UnboundLocalError exception and how to avoid it?

entry

How do I modify a string in python?

senior

Why aren't Python nested functions called closures?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào