+ 1

C++ to Python

In c++ we use pointers for reference to variables in function parameters, but in Python there is no concept of Pointers. So how can we implement the two choices of functional calls i.e. call by value and call by reference in Python.

13th Jul 2020, 2:18 PM
Kewal Sharma
Kewal Sharma - avatar
8 odpowiedzi
+ 1
In python, all objects are transfered by reference. However, some objects are immuable, and their modification implies the creation of a modified copy of the object. Any user-defined data-type is by default considered as mutable. You can use the ctypes library, that contains a real pointer datatype but... I'm not sure it is a good way. If you want to simulate pointers, on basic types, you could do wrappers around native objects : class Wrapper: def __init__(self, value): self.value = value But there is no real way to have pointers in Python.
13th Jul 2020, 4:55 PM
Théophile
Théophile - avatar
+ 1
Lists act as a pointer. Use list for call by reference and normal variable passing for call by value. Sure lists do take a lot of memory but it'll help you. e.g. def func(a): a[0] += 1 a = [5] func(a) print(a[0]) Link to code for your reference: https://code.sololearn.com/cc1A5NDY3Svw/#py
13th Jul 2020, 9:25 PM
Milind Yadav
Milind Yadav - avatar
+ 1
Milind Yadav it is not a matter of 'normal variable' or 'list'. It is a matter of mutability, as I explained previously. And you're actually saying the same thing as I said : creating a wrapper object around another object.
13th Jul 2020, 10:11 PM
Théophile
Théophile - avatar
+ 1
Yep.. that's true.... unfortunately there is no other way....this was just a short code.... that's why I mentioned this
13th Jul 2020, 10:14 PM
Milind Yadav
Milind Yadav - avatar
0
We are using the OOPS concept to overcome this problem
13th Jul 2020, 6:14 PM
J Santhosh Kumar
J Santhosh Kumar - avatar
0
J Santhosh Kumar But OOP is also available in c++, I don't think that can be used here. Please read the question again.
13th Jul 2020, 6:19 PM
Kewal Sharma
Kewal Sharma - avatar
0
Yeah but In python there is no pointers. They using only OOPS concept.
13th Jul 2020, 6:28 PM
J Santhosh Kumar
J Santhosh Kumar - avatar
0
Yes, I'd loved to see pointers too... But at the end, I never really needed them in Python.
13th Jul 2020, 10:16 PM
Théophile
Théophile - avatar