python:获取构造函数以返回现有对象而不是新对象

max*_*max 3 python constructor

我有一个知道其现有实例的类。有时我希望类构造函数返回一个现有对象而不是创建一个新对象。

class X:
    def __new__(cls, arg):
        i = f(arg)
        if i:
            return X._registry[i]
        else:
            return object.__new__(cls)
    # more stuff here (such as __init_, _registry, etc.)
Run Code Online (Sandbox Code Playgroud)

当然,如果第一个分支被执行,我不需要__init__,但它无论如何都会被调用。告诉__init__什么都不做的好方法是什么?

我可能只是添加一些属性来跟踪是否__init__已运行,但也许有更好的方法?

Son*_*rds 10

在支持私有构造函数的语言(C#、Dart、Scala 等)中,工厂方法为这个问题提供了一个强大的解决方案。

然而,在 Python 中,类构造函数始终是可访问的,因此类的用户可能很容易忘记工厂方法并直接调用构造函数,从而产生应该唯一的对象的重复副本。

使用元类可以实现对这个问题的万无一失的解决方案。下面的示例假定第零个构造函数参数可用于唯一标识每个实例:

class Unique(type):

    def __call__(cls, *args, **kwargs):
        if args[0] not in cls._cache:
            self = cls.__new__(cls, *args, **kwargs)
            cls.__init__(self, *args, **kwargs)
            cls._cache[args[0]] = self
        return cls._cache[args[0]]

    def __init__(cls, name, bases, attributes):
        super().__init__(name, bases, attributes)
        cls._cache = {}
Run Code Online (Sandbox Code Playgroud)

它可以按如下方式使用:

class Country(metaclass=Unique):
    def __init__(self, name: str, population: float, nationalDish: str):
        self.name = name
        self.population = population
        self.nationalDish = nationalDish

placeA = Country("Netherlands", 16.8e6, "Stamppot")
placeB = Country("Yemen", 24.41e6, "Saltah")
placeC = Country("Netherlands", 11, "Children's tears")

print(placeA is placeB)    # -> False
print(placeA is placeC)    # -> True
print(placeC.nationalDish) # -> Stamppot
Run Code Online (Sandbox Code Playgroud)

总之,如果您想在运行时生成一组唯一的对象(可能使用其中条目可能重复的数据),则此方法很有用。