这个变量`instantiated`的范围是什么

时间:2015-08-13 21:18:28

标签: python class singleton

我遇到了Peter Norvig在这里的单身课程的实施http://norvig.com/python-iaq.html

def singleton(object, instantiated=[]):
    "Raise an exception if an object of this class has been instantiated before."
    assert object.__class__ not in instantiated, \
        "%s is a Singleton class but is already instantiated" % object.__class__
    instantiated.append(object.__class__)

class YourClass:
    "A singleton class to do something ..."
    def __init__(self, args):
       singleton(self)
       ...

我的问题是,如果我们第二次创建两个YourClass实例,为什么instantiated不是空列表? instantiated的范围是什么?

谢谢。

1 个答案:

答案 0 :(得分:1)

来自docs

  

重要警告:默认值仅评估一次。当默认值是可变对象(如列表,字典或大多数类的实例)时,这会有所不同。它累积了后续调用时传递给它的参数。

@comments = @post.comments.order(created_at: :desc)的值绑定到函数定义,并在定义instantiated时仅初始化一次。

因此,每次调用该函数时,您只有一个相同列表的副本:

singleton

与:

相同
def test(x, instantiated=[]):
    instantiated.append(x)
    print instantiated

>>> test(3)
[3]
>>> test(5)
[3, 5]
>>> test(6)
[3, 5, 6]

如果您希望在后续函数调用之间隔离>>> lst = [] >>> def test(x, instantiated): ... instantiated.append(x) ... print instantiated >>> test(3, lst) [3] >>> test(5, lst) [3, 5] >>> test(6, lst) [3, 5, 6] ,则应将其定义为instantiated

local variable