【问题标题】:During instantiation of a class how to check if an object of that class already exists and if it does, point to the already existing object? [duplicate]在类的实例化期间如何检查该类的对象是否已经存在,如果存在,则指向已经存在的对象? [复制]
【发布时间】:2019-03-28 21:52:45
【问题描述】:

我在一次采访中被问到这个问题。我尝试做的事情如下:

class A:
    l = []
    def __init__(self):
        if len(A.l)==0:
            A.l.append(self)
        else:
            return A.l[0]

a = A()
b = A()

我回到家并运行了这段代码,发现它不起作用。

所以我想知道解决这个问题的正确方法是什么。预期的结果是,当第二次调用A() 时,b 应该指向已经存储在a 中的对象(第一次创建的对象)。

【问题讨论】:

  • 以防万一有人想知道,我没有得到这份工作。
  • 很难过 :( 无论如何市场上有很多鱼(我的意思是工作)。

标签: python


【解决方案1】:

你想实现像 Singleton 这样的东西。最简单的方法是覆盖 __new__ 而不是 __init__

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多