soralley
V2EX  ›  问与答

python 类与实例

  •  
  •   soralley · Oct 10, 2013 · 3749 views
    This topic created in 4779 days ago, the information mentioned may be changed or developed.
    class A:
    def __init__(self, aList = []):
    self.aList = aList

    x = A()
    y = A()

    x.aList.append(...)为什么会影响到y.aList值?aList是共享的属性?怎样分离开来?
    7 replies  •  1970-01-01 08:00:00 +08:00
    soralley
    soralley
    OP
    Oct 10, 2013
    1
    发现self.aList = aList[:]这样就可以分离开来了,但好像不容易理解,还请高手解疑!
    tedd
    tedd
    Oct 10, 2013
    2
    参数最好不要用可变的类型吧,很容易相互相应到的
    est
    est
    Oct 10, 2013
    3
    def __init__(self, aList = []):

    这里的 [] 其实是隐含申明成全局变量了。

    def __init__(self, aList = None):
    if not aList: aList = []

    这样ok了。
    clino
    clino
    Oct 10, 2013
    4
    好像 http://v2ex.com/t/75013 说的就是这个吧
    如果用
    x = A([])
    y = A([])
    就不会了,或者
    def __init__(self, aList = None):
    if aList==None:aList = []
    self.aList = aList
    这样也可以
    soralley
    soralley
    OP
    Oct 10, 2013
    5
    最新发现,把默认参数拉长了就不会,好像是编译优化的问题,恩,好像
    est兄正解
    dreampuf
    dreampuf
    Oct 10, 2013
    6
    In [75]: def FuncA(ls=[]): ls.append(1)

    In [76]: FuncA.func_defaults
    Out[76]: ([],)

    In [77]: FuncA()

    In [78]: FuncA.func_defaults
    Out[78]: ([1],)

    In [79]: FuncA()

    In [80]: FuncA.func_defaults
    Out[80]: ([1, 1],)
    piglei
    piglei
    Oct 10, 2013
    7
    不要使用可变类型来作为方法的默认值,具体可以了解:
    http://effbot.org/zone/default-values.htm
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4256 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 06:01 · PVG 14:01 · LAX 22:01 · JFK 01:01
    ♥ Do have faith in what you're doing.