Maison  >  Article  >  développement back-end  >  Comprendre l'affectation et la copie de Python

Comprendre l'affectation et la copie de Python

零到壹度
零到壹度original
2018-04-19 15:24:021034parcourir

Les exemples de cet article décrivent la compréhension de l'affectation et de la copie de Python. Partagez-le avec tout le monde pour votre référence, les détails sont les suivants :

Variables et affectation

En Python, tout est un objet, et les objets sont représentés par une référence "variables" "nom", "nom de variable" est plus précisément appelé "nom", tout comme chacun de nous a son propre nom, nous nous référons à une personne par son nom et un objet est désigné par son nom dans le code.

L'affectation de variable consiste à lier un nom à l'objet L'affectation ne copie pas l'objet. Tout comme nos parents nous donnent un nom à notre naissance, donner un surnom à quelqu'un ne crée pas une personne supplémentaire, cela crée simplement un nom supplémentaire.

Il existe deux façons de comparer deux objets, à savoir : is et ==, is Ce qui est comparé est de savoir si les deux objets sont identiques. Le fait qu'il s'agisse du même objet peut être identifié par la valeur ID. de l'objet, == Ce qui est comparé est de savoir si les valeurs​​des deux objets sont égales

<code class="hljs language-python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x1 = [<span class="hljs-number" style="color:rgb(0,128,128);">1</span>,<span class="hljs-number" style="color:rgb(0,128,128);">2</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x2 = [<span class="hljs-number" style="color:rgb(0,128,128);">1</span>,<span class="hljs-number" style="color:rgb(0,128,128);">2</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x1 <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> x2<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">False</span><br><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>id(x1)<br><span class="hljs-number" style="color:rgb(0,128,128);">4338854088</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>id(x2)<br><span class="hljs-number" style="color:rgb(0,128,128);">4338904392</span><br><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x1 == x2<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">True</span></code>

Bien que les valeurs​​de x1 et x2 soient les mêmes, elles sont deux objets indépendants et différents dans la mémoire, occupant des espaces mémoire différents, tout comme deux Deux pommes qui se ressemblent sont placées sur la table, mais ce sont en fait deux objets différents.

<code class="hljs language-python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x3 = x2<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x3 <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> x2<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">True</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>id(x3)<br><span class="hljs-number" style="color:rgb(0,128,128);">4338904392</span></code>

Comme mentionné précédemment, l'affectation consiste à lier un nom à un objet. Ici, nous lions simplement un nouveau nom appelé x3 à l'objet correspondant à x2. C'est comme mettre une pomme initialement attachée à une étiquette de. x2, puis j'y ai ajouté une étiquette x3. Il s'agit essentiellement de la même pomme, donc x2 et x3 font en fait référence au même objet.

Comprendre laffectation et la copie de Python

Lorsque l'objet est modifié via x2, x3 changera également car il s'agit essentiellement du même objet. C'est comme lorsque Zhang San et Xiao Zhang sont la même personne, ajoutant. Les vêtements de Zhang San ajoutent en fait des vêtements à Xiao Zhang.

<code class="hljs language-python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x2.append(<span class="hljs-number" style="color:rgb(0,128,128);">3</span>)<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x2<br>[<span class="hljs-number" style="color:rgb(0,128,128);">1</span>, <span class="hljs-number" style="color:rgb(0,128,128);">2</span>, <span class="hljs-number" style="color:rgb(0,128,128);">3</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x3<br>[<span class="hljs-number" style="color:rgb(0,128,128);">1</span>, <span class="hljs-number" style="color:rgb(0,128,128);">2</span>, <span class="hljs-number" style="color:rgb(0,128,128);">3</span>]</code>

Cependant, lorsque je réattribue une valeur à x2, cela signifie que x2 ne fait plus référence à l'objet précédent, mais fait référence au nouvel objet, et x3 fait toujours référence à l'objet précédent. Par exemple, une grosse pomme sur la table a deux étiquettes : x2 et x3. Réattribuer une valeur à x2 équivaut à attacher l'étiquette x2 à une autre pomme, mais x3 est toujours attaché à l'ancienne pomme.

<code class="hljs language-python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x2 = [<span class="hljs-number" style="color:rgb(0,128,128);">3</span>, <span class="hljs-number" style="color:rgb(0,128,128);">4</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x3<br>[<span class="hljs-number" style="color:rgb(0,128,128);">1</span>, <span class="hljs-number" style="color:rgb(0,128,128);">2</span>, <span class="hljs-number" style="color:rgb(0,128,128);">3</span>]</code>

Comprendre laffectation et la copie de Python

Copie d'objet

En entreprise, on a parfois besoin de copier un objet, mais on ne veut pas avoir des effets secondaires sur l'objet d'origine, cela ne peut certainement pas être résolu en attribuant une valeur à une nouvelle variable (car l'affectation n'est pas une copie de l'objet), donc Python fournit spécifiquement un mécanisme de copie pour créer rapidement un objet contenant la même valeur. basé sur l'objet original. Cette fonctionnalité est assurée par le module copy.


La copie est divisée en copie superficielle et copie profonde.

>>> s = [1,2,3]
>>> sc = copy.copy(s) # 浅拷贝
>>> sc
[1, 2, 3]
<code class="hljs language-python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>sdc = copy.deepcopy(s)  <span class="hljs-comment" style="color:rgb(153,153,136);font-style:italic;"># 深拷贝</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>sdc<br>[<span class="hljs-number" style="color:rgb(0,128,128);">1</span>, <span class="hljs-number" style="color:rgb(0,128,128);">2</span>, <span class="hljs-number" style="color:rgb(0,128,128);">3</span>]</code>

Les objets copiés n'ont que la même valeur, mais sont en fait des objets différents

<code class="hljs language-python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>s == sc == sdc <br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">True</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>s <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> sc <br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">False</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>s <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> sdc<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">False</span></code>

Alors, quelle est la différence entre une copie superficielle et une copie profonde ? ?

Pour les objets immuables, tels que les entiers, les chaînes, les tuples et les objets de collection composés de ces objets immuables, il n'y a pas de différence entre la copie superficielle et la copie profonde, les deux copient un nouvel objet

两者的区别在于拷贝组合对象,比如列表中还有列表,字典中还有字典或者列表的情况时,浅拷贝只拷贝了外面的壳子,里面的元素并没有拷贝,而深拷贝则是把壳子和里面的元素都拷贝了一份新的。

来看一个例子:

<code class="hljs language-python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x = [<span class="hljs-number" style="color:rgb(0,128,128);">2</span>, <span class="hljs-number" style="color:rgb(0,128,128);">3</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>y = [<span class="hljs-number" style="color:rgb(0,128,128);">7</span>, <span class="hljs-number" style="color:rgb(0,128,128);">11</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>z = [x, y]<br><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>a = copy.copy(z) <span class="hljs-comment" style="color:rgb(153,153,136);font-style:italic;"># 浅拷贝</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>a[<span class="hljs-number" style="color:rgb(0,128,128);">0</span>] <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> z[<span class="hljs-number" style="color:rgb(0,128,128);">0</span>]<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">True</span></code>

Comprendre laffectation et la copie de Python

拷贝出来的对象 a 中的元素引用的是 x 和 y,当你修改 x 的值,a 也会跟着变。

<code class="hljs language-python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);text-align:justify;"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>b = copy.deepcopy(z) <span class="hljs-comment" style="color:rgb(153,153,136);font-style:italic;"># 深拷贝</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>b[<span class="hljs-number" style="color:rgb(0,128,128);">0</span>] <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> z[<span class="hljs-number" style="color:rgb(0,128,128);">0</span>]<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">False</span></code>

Comprendre laffectation et la copie de Python

对于深拷贝,里面的元素也重新拷贝了一份,拷贝了一份与x和y等值的两个元素,修改 x 和 y 的值,不会对 b 产生影响


对列表的切片拷贝 z[:] 或者是调用对象的copy方法 list.copy() 都属于浅拷贝。对于自定义对象,我们还可以自己实现 __copy__方法和 __deepcopy__方法


相关阅读:

Django入门实践指南-第1部分
厉害了,10行代码实现抽奖助手自动参与抽奖
看了很多代码,却依然无从下手?

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn