Answer the question
In order to leave comments, you need to log in
How to use pointers in python?
How to implement this behavior in python?
#include <iostream>
using namespace std;
void change(char* a, char* b)
{
char temp = *a;
*a = *b;
*b = temp;
}
int main(void)
{
char a = 'x';
char b = 'y';
printf("a=%c, b=%c\n", a, b);
change(&a, &b);
printf("a=%c, b=%c\n", a, b);
}
Answer the question
In order to leave comments, you need to log in
Hell yes! It's possible. Of course, at the moment there is a variant with a bunch of crutches, but they can be greatly improved.
>> s = 'string'
>> w = Proxy(s)
>> isinstance(w, str), id(w)
True, 1680141601288
>> print(w)
string
>> w.__wrapped__ = [1, 2, 3]
>> isinstance(w, list), id(w)
True, 1680141601288
>> print(w)
[1, 2, 3]
Well, the banal one x, y = y, x
will do the same, no? (Now I'm trying to remember how it was in dereferences ;)). and pypy is the same python, but with JIT compilation
Here, it seems, there is a misunderstanding of how variables are arranged in python and how they differ from variables (and partly pointers) in C.
In C (and not only, in Pascal, for example, too) a variable is a box that already exists and you can put something into it by replacing some garbage that was there before, then its contents can be replaced.
In Python, a variable is like a label. The label is the name, and everything around is the objects. You can hang many tags on one object (think of a tea bag tag). Each label is a separate name or position in a list, tuple, dictionary...) There is only one object, but there can be many references to it. The label can be destroyed or moved to another object. When there is not a single label attached to an object, it becomes a candidate for deletion and release of memory.
You were shown in an adjacent answer how you can elegantly exchange names of two objects in python. Yes, exactly, the names will change places, but the objects will remain as they were. It's like changing the plates on the offices of the director and chief accountant.
So, in a way, all variables in python are smart weak references.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question