zoukankan      html  css  js  c++  java
  • Objects and values

    If we execute these assignment statements:

                           

    We know that a and b both refer to a string, but we don’t know whether they refer to the same string. To check whether two variables refer to the same object, you can use the is operator. And the result shows in this example, Python only created one string object, and both a and b refer to it.

    In contrast, when you create two lists, you get two objects:

     

    In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical. Until now, we have been using ‘Object’ and ‘value’ interchangeably, but it is more precise to say that an object has a value. If you execute a = [1,2,3], a refers to a list object whose value is a particular sequence of elements. If another list has the same elements, we would say it has the same value.

    Aliasing

    If a refers to an object and you assign b = a, then both variables refer to the same object. For example if you execute:

     

     

    The association of a variable with an object is called reference. In this example, there are two references to the same object. An object with more than one reference has, in some sense, more than one name, so we say that the object is aliased. If the aliased object is mutable, changes made with one alias affect the other:

     

    Although this behaviour can be useful, it is sometimes unexpected or undesirable. In general, it is safer to avoid aliasing when you are working with mutable objects. For immutable objects like strings, aliasing is not as much of a problem. For example string, it almost never makes a difference whether a and b refer to the same string or not.

     

     

    from Thinking in Python

  • 相关阅读:
    Fortran编译器之一GUN Fortran安装(Windows XP)
    c++动态绑定的技术实现
    c++标准库比较
    java array
    java常用的基础容器
    mac sublime text 3 add ctags plugin
    git fetch
    查看远程分支的log
    git删除分支
    detached HEAD state
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/3841505.html
Copyright © 2011-2022 走看看