这个变量的作用域是什么`

2024-04-29 09:12:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里遇到了peternorvig的单例类实现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的范围是什么

谢谢你


Tags: selfcomanhttpobjectisdefclass
1条回答
网友
1楼 · 发布于 2024-04-29 09:12:06

docs

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. It accumulates the arguments passed to it on subsequent calls.

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

def test(x, instantiated=None):
    if instantiated is None:
        instantiated = []
    instantiated.append(x)
    print instantiated

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

相关问题 更多 >