加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 13:52:06 所属栏目:Python 来源:网络整理
导读:我在 http://norvig.com/python-iaq.html遇到了Peter Norvig的单身人士课程 def singleton(object,instantiated=[]): "Raise an exception if an object of this class has been instantiated before." assert object.__class__ not in instantiated, "%s i
我在 http://norvig.com/python-iaq.html遇到了Peter Norvig的单身人士课程

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实例,在第二次,为什么实例化不是一个空列表?实例化的范围是什么?

谢谢.

解决方法

从 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.

实例化的值绑定到函数定义,并且在定义单例时仅初始化一次.

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

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,6]

如果要在后续函数调用之间隔离实例化,则应将其定义为局部变量:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读