Programing

두 변수가 파이썬에서 동일한 객체를 참조하는지 비교

crosscheck 2020. 9. 22. 07:31
반응형

두 변수가 파이썬에서 동일한 객체를 참조하는지 비교


두 변수가 동일한 객체를 참조하는지 확인하는 방법은 무엇입니까?

x = ['a', 'b', 'c']
y = x                 # x and y reference the same object
z = ['a', 'b', 'c']   # x and z reference different objects

그 이유 is는 다음 같습니다. 동일한 객체 인 경우 x is y반환 합니다.Truexy


y is xTrue, y is z될 것입니다 False.


두 가지 올바른 솔루션 x is zid(x) == id(z)파이썬 구현 세부 사항을 지적하고 싶습니다. 파이썬은 정수를 객체로 저장합니다. 최적화로 시작 부분 (-5 ~ 256)에 작은 정수 묶음을 생성하고 이러한 사전 초기화 된 객체에 대해 작은 값을 가진 정수를 보유하는 모든 변수를 가리 킵니다. 더 많은 정보

즉, 동일한 작은 숫자 (-5 ~ 256)로 초기화 된 정수 개체의 경우 두 개체가 동일한 지 확인하면 true를 반환하지만 (C-Pyhon에서는 이것이 구현 세부 사항이라는 것을 알고있는 한) 하나의 객체가 다른 객체에서 초기화 된 경우에만 true를 반환합니다.

> i = 13
> j = 13
> i is j
True

> a = 280
> b = 280
> a is b
False

> a = b
> a
280
> a is b
True

또한 id ()사용 하여 각 변수 이름이 참조하는 고유 한 개체를 확인할 수 있습니다 .

In [1]: x1, x2 = 'foo', 'foo'

In [2]: x1 == x2
Out[2]: True

In [3]: id(x1), id(x2)
Out[3]: (4509849040, 4509849040)

In [4]: x2 = 'foobar'[0:3]

In [5]: x2
Out[5]: 'foo'

In [6]: x1 == x2
Out[6]: True

In [7]: x1 is x2
Out[7]: False

In [8]: id(x1), id(x2)
Out[8]: (4509849040, 4526514944)

저는 시각적 인 피드백을 받고 싶어요. 그래서 가끔 http://www.pythontutor.com/visualize.html#mode=edit열어서 메모리가 어떻게 할당되고 무엇을 참조하는지 확인합니다.

enter image description here

이 댓글은 시각화에 관한 것이므로이 멋진 gif를 추가했습니다.


This is from docs.python.org: "Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is’ operator compares the identity of two objects; the id() function returns an integer representing its identity."

Apparently every time you change the value the object is recreated as indicated by the identity changing. The line x=3 followed by the line x=3.14 gives no error & gives different identities, types and values for x.

참고URL : https://stackoverflow.com/questions/5445080/compare-if-two-variables-reference-the-same-object-in-python

반응형