这个变量“实例化”的范围是什么
What is the scope of this variable `instantiated`
我在这里看到了 Peter Norvig 的单例实现 class 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
的范围是什么?
谢谢。
来自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]
我在这里看到了 Peter Norvig 的单例实现 class 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
的范围是什么?
谢谢。
来自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]