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.

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.

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.

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

What does the Python nonlocal statement do (in Python 3.0 and later)?

senior

How is memory managed in Python?

junior

What are local variables and global variables in Python?

Bình luận

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

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