id () 함수는 무엇에 사용됩니까?
Python 2 문서를 읽고 id()
함수를 발견했습니다 .
객체의 "ID"를 반환합니다. 이는 수명 동안이 개체에 대해 고유하고 일정하게 보장되는 정수 (또는 긴 정수)입니다. 수명이 겹치지 않는 두 개체는 동일한 id () 값을 가질 수 있습니다.
CPython 구현 세부 사항 : 이것은 메모리에있는 오브젝트의 주소입니다.
그래서 id()
목록 을 사용하여 실험했습니다 .
>>> list = [1,2,3]
>>> id(list[0])
31186196
>>> id(list[1])
31907092 // increased by 896
>>> id(list[2])
31907080 // decreased by 12
함수에서 반환 된 정수는 무엇입니까? C의 메모리 주소와 동의어입니까? 그렇다면 정수가 데이터 유형의 크기와 일치하지 않는 이유는 무엇입니까?
id()
실제로 언제 사용됩니까?
귀하의 게시물에는 몇 가지 질문이 있습니다.
함수에서 반환 된 숫자는 무엇입니까?
" 수명 동안이 객체에 대해 고유하고 상수가 보장되는 정수 (또는 긴 정수)입니다. " (Python 표준 라이브러리-내장 함수) 고유 한 숫자입니다. 그 이상도 그 이하도 아닙니다. Python 객체에 대한 사회 보장 번호 또는 직원 ID 번호로 생각하십시오.
C의 메모리 주소와 동일합니까?
개념적으로는 그렇습니다. 둘 다 평생 동안 우주에서 독특함을 보장한다는 점에서 그렇습니다. 그리고 파이썬의 특정 구현에서는 실제로 해당 C 객체의 메모리 주소입니다.
그렇다면 데이터 유형의 크기만큼 숫자가 즉시 증가하지 않는 이유는 무엇입니까 (정수라고 가정합니다)?
목록은 배열이 아니고 목록 요소는 객체가 아니라 참조이기 때문입니다.
우리는 언제 실제로
id( )
기능을 사용 합니까?
거의 없습니다. id()
(또는 이에 상응하는) is
연산자 가 사용됩니다 .
그것은 메모리에있는 물체 의 위치 에 대한 정체입니다 .
이 예는 개념을 좀 더 이해하는 데 도움이 될 수 있습니다.
foo = 1
bar = foo
baz = bar
fii = 1
print id(foo)
print id(bar)
print id(baz)
print id(fii)
> 1532352
> 1532352
> 1532352
> 1532352
이들은 모두 메모리에서 동일한 위치를 가리 키므로 값이 동일한 것입니다. 이 예에서는 1
한 번만 저장되며 다른 모든 항목 1
은 해당 메모리 위치를 참조합니다.
id()
참조되는 객체의 주소를 반환하지만 (CPython에서) 파이썬 목록이 C 배열과 매우 다르다는 사실에서 혼란이 발생합니다. 파이썬 목록에서 모든 요소는 참조 입니다. 그래서 당신이하는 일은이 C 코드와 훨씬 더 비슷합니다.
int *arr[3];
arr[0] = malloc(sizeof(int));
*arr[0] = 1;
arr[1] = malloc(sizeof(int));
*arr[1] = 2;
arr[2] = malloc(sizeof(int));
*arr[2] = 3;
printf("%p %p %p", arr[0], arr[1], arr[2]);
In other words, you are printing the address from the reference and not an address relative to where your list is stored.
In my case, I have found the id()
function handy for creating opaque handles to return to C code when calling python
from C. Doing that, you can easily use a dictionary to look up the object from its handle and it's guaranteed to be unique.
I am starting out with python and I use id when I use the interactive shell to see whether my variables are assigned to the same thing or if they just look the same.
Every value is an id, which is a unique number related to where it is stored in the memory of the computer.
If you're using python 3.4.1 then you get a different answer to your question.
list = [1,2,3]
id(list[0])
id(list[1])
id(list[2])
returns:
1705950792
1705950808 # increased by 16
1705950824 # increased by 16
The integers -5
to 256
have a constant id, and on finding it multiple times its id does not change, unlike all other numbers before or after it that have different id's every time you find it. The numbers from -5
to 256
have id's in increasing order and differ by 16
.
The number returned by id()
function is a unique id given to each item stored in memory and it is analogy wise the same as the memory location in C.
Rob's answer (most voted above) is correct. I would like to add that in some situations using IDs is useful as it allows for comparison of objects and finding which objects refer to your objects.
The later usually helps you for example to debug strange bugs where mutable objects are passed as parameter to say classes and are assigned to local vars in a class. Mutating those objects will mutate vars in a class. This manifests itself in strange behavior where multiple things change at the same time.
Recently I had this problem with a Python/Tkinter app where editing text in one text entry field changed the text in another as I typed :)
Here is an example on how you might use function id() to trace where those references are. By all means this is not a solution covering all possible cases, but you get the idea. Again IDs are used in the background and user does not see them:
class democlass:
classvar = 24
def __init__(self, var):
self.instancevar1 = var
self.instancevar2 = 42
def whoreferencesmylocalvars(self, fromwhere):
return {__l__: {__g__
for __g__ in fromwhere
if not callable(__g__) and id(eval(__g__)) == id(getattr(self,__l__))
}
for __l__ in dir(self)
if not callable(getattr(self, __l__)) and __l__[-1] != '_'
}
def whoreferencesthisclassinstance(self, fromwhere):
return {__g__
for __g__ in fromwhere
if not callable(__g__) and id(eval(__g__)) == id(self)
}
a = [1,2,3,4]
b = a
c = b
democlassinstance = democlass(a)
d = democlassinstance
e = d
f = democlassinstance.classvar
g = democlassinstance.instancevar2
print( 'My class instance is of', type(democlassinstance), 'type.')
print( 'My instance vars are referenced by:', democlassinstance.whoreferencesmylocalvars(globals()) )
print( 'My class instance is referenced by:', democlassinstance.whoreferencesthisclassinstance(globals()) )
OUTPUT:
My class instance is of <class '__main__.democlass'> type.
My instance vars are referenced by: {'instancevar2': {'g'}, 'classvar': {'f'}, 'instancevar1': {'a', 'c', 'b'}}
My class instance is referenced by: {'e', 'd', 'democlassinstance'}
Underscores in variable names are used to prevent name colisions. Functions use "fromwhere" argument so that you can let them know where to start searching for references. This argument is filled by a function that lists all names in a given namespace. Globals() is one such function.
The answer is pretty much never. IDs are mainly used internally to Python.
The average Python programmer will probably never need to use id()
in their code.
It is the address of the object in memory, exactly as the doc says. However, it has metadata attached to it, properties of the object and location in the memory is needed to store the metadata. So, when you create your variable called list, you also create metadata for the list and its elements.
So, unless you an absolute guru in the language you can't determine the id of the next element of your list based on the previous element, because you don't know what the language allocates along with the elements.
The is
operator uses it to check whether two objects are identical (as opposed to equal). The actual value that is returned from id()
is pretty much never used for anything because it doesn't really have a meaning, and it's platform-dependent.
I have an idea to use value of id()
in logging.
It's cheap to get and it's quite short.
In my case I use tornado and id()
would like to have an anchor to group messages scattered and mixed over file by web socket.
As of in python 3 id is assigned to a value not a variable. This means that if you create two functions as below, all the three id's are the same.
>>> def xyz():
... q=123
... print(id(q))
...
>>> def iop():
... w=123
... print(id(w))
>>> xyz()
1650376736
>>> iop()
1650376736
>>> id(123)
1650376736
참고URL : https://stackoverflow.com/questions/15667189/what-is-the-id-function-used-for
'IT story' 카테고리의 다른 글
Django Forms : 유효하지 않은 경우 오류 메시지와 함께 양식 표시 (0) | 2020.08.31 |
---|---|
Pandas 또는 Numpy Nan을 None으로 대체하여 MysqlDB와 함께 사용 (0) | 2020.08.31 |
Swift를 사용하여 NSDates를 정수로 초 단위로 찾기 (0) | 2020.08.31 |
1이 아닌 2 열에서 중복을 찾는 방법 (0) | 2020.08.31 |
NetBeans에서 파일 인코딩을 변경하는 방법은 무엇입니까? (0) | 2020.08.31 |