V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
eailfly
V2EX  ›  Python

如何判断一个列表是否存在?存在就添加项,否则就新建列表。

  •  
  •   eailfly · 2015-02-05 11:44:18 +08:00 · 3325 次点击
    这是一个创建于 3360 天前的主题,其中的信息可能已经有所发展或是发生改变。

    具体是这样的,我有一个类,里面定义了一个列表,

    class song(object):
    def play(name):
    if 'songlist' not in dir():
    songlist = [name]
    else:
    songlist.append(name)

    然后我调用这个类,

    a = song()
    a.play('abc')

    但是貌似这样列表一直都是空的,应该怎样定义列表呢?

    9 条回复    2015-02-09 17:15:20 +08:00
    roricon
        1
    roricon  
       2015-02-05 12:38:58 +08:00
    因为你类的实例里面,没有变量保持对'songlist'的引用,所以这个列表被垃圾回收了……
    试着改成这样
    https://gist.github.com/anonymous/f85d63702c76f078a3c4
    roricon
        2
    roricon  
       2015-02-05 12:42:44 +08:00
    messense
        3
    messense  
       2015-02-05 12:51:46 +08:00   ❤️ 1
    class song(object):
    ----def __init__(self):
    --------self.songlist = set()

    ----def play(self, name):
    --------self.songlist.add(name)
    repus911
        4
    repus911  
       2015-02-05 13:03:03 +08:00
    @roricon 类参数的第一个应该是self,还有这种设置默认参数的方式很有问题
    3楼正解
    roricon
        5
    roricon  
       2015-02-05 13:05:11 +08:00
    @repus911 不用IDE感觉整个人都废了,忘记写self,3楼是正确的。
    这种设置默认参数有什么问题?意思是应该直接用'[]'?
    hahastudio
        6
    hahastudio  
       2015-02-05 13:34:05 +08:00
    @roricon 不用 [] 用 list() 说明你知道这个常见的错误
    但是你没理解
    比如我要是
    l = ["a"]
    s = song(l)
    这就完了,因为保留的是引用
    如果真需要传一个 list 当参数,且不需要 side effect 的话,试试深拷贝一个:
    self.songlist = songlist[:]
    repus911
        7
    repus911  
       2015-02-05 18:56:20 +08:00
    @hahastudio
    你说的是一方面
    函数声明的默认参数会作为一个变量保存在函数的域里面,所以你会发现
    class A(object):
    def __init__(self, data=list()): # 或者data=[]
    self.data = data

    a = A()
    a.data.append(1)

    b = A()
    print b.data
    >>> [1]

    正确的做法是像3楼那样,在函数内判断data是否为空,为空在局部生成一个。

    @roricon
    ruoyu0088
        8
    ruoyu0088  
       2015-02-07 22:26:08 +08:00
    如果要判断全局变量中是否有某个名字:if name in globals()
    如果要判断某个实例是否包行某个属性:if hasattr(self, name)
    eailfly
        9
    eailfly  
    OP
       2015-02-09 17:15:20 +08:00
    3楼方法解决了问题,谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1250 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 17:51 · PVG 01:51 · LAX 10:51 · JFK 13:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.