Skip to content

请教关于引用的一个问题 #98

Description

@xiaoyan94

a
[9, 7, 5, 3, 1]
b
[9, 7, 5, 3, 1]
a.reverse()
a
[1, 3, 5, 7, 9]
b
[1, 3, 5, 7, 9] #为什么这里b也会变?

Activity

  1. lambdaplus commented on May 5, 2016

    @lambdaplus
    Contributor

    In [13]: a = [9, 7, 5, 3, 1]
    
    In [14]: b = a
    
    In [15]: b
    Out[15]: [9, 7, 5, 3, 1]
    
    In [16]: a.reverse()
    
    In [17]: a
    Out[17]: [1, 3, 5, 7, 9]
    
    In [18]: b
    Out[18]: [1, 3, 5, 7, 9]

    上面的a和b其实是指向的同一个内存地址,修改任一个的值,都会影响到另一个。

    In [26]: a.__str__
    Out[26]: <method-wrapper '__str__' of list object at 0x7fc1f7f68988>
    
    In [27]: b.__str__
    Out[27]: <method-wrapper '__str__' of list object at 0x7fc1f7f68988>

    下面是n是m的拷贝,m、n内存地址不同。

    In [24]: m.__str__
    Out[24]: <method-wrapper '__str__' of list object at 0x7fc1f7f6fdc8>
    
    In [25]: n.__str__
    Out[25]: <method-wrapper '__str__' of list object at 0x7fc1f7e6bdc8>
    In [19]: m = [0, 2, 4, 6, 8]
    
    In [20]: n = m.copy()
    
    In [21]: m.reverse()
    
    In [22]: m
    Out[22]: [8, 6, 4, 2, 0]
    
    In [23]: n
    Out[23]: [0, 2, 4, 6, 8]

    再深一点就是__深拷贝和浅拷贝__了
    个人愚见。

  2. qiwsir commented on May 5, 2016

    @qiwsir
    Owner

    有道理。很多高级语言,都是将某些基本类型和由基本类型组合的类型,以不同的存储方式处理。

    2016-05-05 17:04 GMT+08:00 lambdaplus notifications@github.com:


    In [13]: a = [9, 7, 5, 3, 1]

    In [14]: b = a

    In [15]: b
    Out[15]: [9, 7, 5, 3, 1]

    In [16]: a.reverse()

    In [17]: a
    Out[17]: [1, 3, 5, 7, 9]

    In [18]: b
    Out[18]: [1, 3, 5, 7, 9]

    上面的a和b其实是指向的_同一个内存地址_,修改任一个的值,都会影响到另一个。

    In [26]: a.str
    Out[26]: <method-wrapper 'str' of list object at 0x7fc1f7f68988>

    In [27]: b.str
    Out[27]: <method-wrapper 'str' of list object at 0x7fc1f7f68988>


    下面是n是m的拷贝,m、n内存地址不同。

    In [24]: m.str
    Out[24]: <method-wrapper 'str' of list object at 0x7fc1f7f6fdc8>

    In [25]: n.str
    Out[25]: <method-wrapper 'str' of list object at 0x7fc1f7e6bdc8>

    In [19]: m = [0, 2, 4, 6, 8]

    In [20]: n = m.copy()

    In [21]: m.reverse()

    In [22]: m
    Out[22]: [8, 6, 4, 2, 0]

    In [23]: n
    Out[23]: [0, 2, 4, 6, 8]

    再深一点就是__深拷贝和浅拷贝__了
    个人愚见。

    —
    You are receiving this because you are subscribed to this thread.
    Reply to this email directly or view it on GitHub
    #98 (comment)

    QiWei

  3. xiaoyan94 commented on May 6, 2016

    @xiaoyan94
    Author

    谢谢!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions