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

  • 相关阅读:
    Python NLPIR(中科院汉语分词系统)的使用 十五分钟快速入门与完全掌握
    Python NLPIR(中科院汉语分词系统)的使用 十五分钟快速入门与完全掌握
    源码:我的关于NLP的博客(持续更新中...)
    源码:我的关于NLP的博客(持续更新中...)
    orm功能封装
    元类
    事件,存储
    索引
    mysql课外积累
    day35作业
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/3841505.html
Copyright © 2011-2022 走看看