Reputation: 322
Would it be correct to say that all Python variables are pointers to pointer (in terms of C) to some data object say int or list? e.g. a = 5 is putting address of object int(5) into a, where a has its own address which is useless (I think).
And print is defined in Python to print the content of the object pointed to by the address stored in a.
And id is defined in Python to print the address stored in a.
Is this what really happening under the hood?
Upvotes: 0
Views: 388
Reputation: 563
Have a look at the quite old, but still relevant, question Are python variables pointers? or else what are they? It's referenced in a good discussion here too.
Yes, you can look at variables in any harvard or von neumann architecture as a "pointer", in that the object has an address in memory. The word you use is different depending on the coding language etc. etc. but pretty soon the discussion becomes a massive tangle of conflicting opinions, as it's just too wide open.
I'm also a C programmer, and when I started using Python I tried to cast all my code in terms of C. It doesn't work, as Python abstracts you from the addressing.
A good example: if you declare two objects in Python, and they both have the same value and type, then they might have the same memory address (check with id() I think). Makes perfect sense to save resources. Only when both are different does Python shift the one object to a different place in memory. In C you "don't" get that, as it is a compiled language, not scripted. If you make it so via a pointer variable... the variable has it's own address and then you have to be very very careful anyway, which is both the power and weakness of C.
There are marked differences between scripted and compiled languages. Anyway, read the question/answer in the link, it's really pretty good.
Upvotes: 4
Reputation: 530833
Not really, but close. A Python variable is a name that refers to an object. Full stop. Python doesn't define any semantics about how this is done.
print
takes an object as its argument. That object can be passed via a literal (print(3)
, print("foo")
, print(True)
), or via a reference (print(a)
).
id
returns an integer identifier that is unique to that object for the lifetime of that object. What that integer is is also not defined by the language; it's up to the implementation to decide. It could just as easily be a serial number that starts with 0 and gets incremented every time a new object is created.
Any question about "under the hood" can only be answered by specifying which implementation of Python you are using, and that answer will not really be of any use in understanding what a particular piece of Python means, only in understanding how a particular implementation does it.
Upvotes: 6