In Python ist alles ein Objekt, von Variablen bis hin zu Listen und Wörterbüchern wird alles als Objekt behandelt. In diesem Artikel werden wir die Speicheradresse eines Objekts in Python abrufen. 

Methode 1: Verwenden von id()

Wir können eine Adresse mit der Funktion id() erhalten. Die Funktion id() gibt die Adresse des jeweiligen Objekts an.

Syntax:

ID (Objekt)

wobei das Objekt die Datenvariablen sind.

Beispiel: Python-Programm, um die Adresse verschiedener Objekte zu erhalten

Python3

# get id of list
a = [1, 2, 3, 4, 5]
print(id(a))
  
# get id of a variable
a = 12
print(id(a))
  
# get id of tuple
a = (1, 2, 3, 4, 5)
print(id(a))
  
# get id of a dictionary
a = {'a': 1, 'b': 2}
print(id(a))

Ausgabe:

140234866534752

94264748411744

140234904267376

140234866093264

Methode 2: Verwendung von c_int, Adresse der Module

ctypes ist eine Fremdfunktionsbibliothek für Python. Es bietet C-kompatible Datentypen und ermöglicht den Aufruf von Funktionen in DLLs oder gemeinsam genutzten Bibliotheken.

Syntax:

Adressevon(c_int(Objekt))

wobei Objekt die Datenvariablen sind

Beispiel: Python-Programm zum Abrufen der Speicheradresse einer Variablen

Python3

# import addressof and c_int modules 
# from ctypes module
from ctypes import c_int, addressof
  
# get memory address of variable
a = 44
print(addressof(c_int(a)))

Ausgabe:

140234866278064

Es ist auch möglich, Speicheradressen im Hexadezimalformat zu erhalten. Hier rufen wir die Funktion hex(address) auf, um die Speicheradresse in eine hexadezimale Darstellung umzuwandeln.

Syntax:

hex(id(objekt))

wo,

  • hex() ist die hexadezimale Speicherdarstellung der Adresse
  • id wird verwendet, um den Speicher des Objekts abzurufen
  • Objekt sind die Daten

Beispiel: Python-Programm, um die Speicheradresse in hexadezimaler Darstellung zu erhalten.

Python3

# get id of list in hexadecimal representation
a = [1, 2, 3, 4, 5]
print(hex(id(a)))
  
# get id of a variable in hexadecimal 
# representation
a = 12
print(hex(id(a)))
  
# get id of tuple in hexadecimal 
# representation
a = (1, 2, 3, 4, 5)
print(hex(id(a)))
  
# get id of a dictionary in hexadecimal 
# representation
a = {'a': 1, 'b': 2}
print(hex(id(a)))

Ausgabe:

0x7fba9b0ae8c0

0x5572da858b60

0x7fba9f3c4a10

0x7fba9b05b8c0