0

Premise:

Suppose I have a variable x and two function f(x) and g(x) such that when f(x) has the ability to change the value of x (maybe it wants to keep track on how many times f(x) has been called) and g(x) doesn't want to change the value of x at any cost.

Now if i was choose x as an integer, I can accomplish g(x) and if x is a list, I can accomplish f(x).

Question:

But what if I want to accomplish both of them in the same program?

What should I do then?.

If its not possible, then doesn't this severely handicap python wrt other languages.

Note:

Basically my question is motivated by finding the drawbacks of not having pointers in python as in other language like C++, the above task can easily be implemented by choosing the *x instead of x.

Leonardo Scotti
  • 1,069
  • 8
  • 21
  • 1
    Maybe read http://stupidpythonideas.blogspot.com/2013/11/does-python-pass-by-value-or-by.html – buran Nov 19 '20 at 16:37

2 Answers2

1

If all you need to do is change the value of a variable that you pass to f, you can simply return the new value:

def f(x):
    return x + 1

x = 30
x = f(x)
# x is now 31

If there is already another value you need to return from f, you can return a tuple and unpack the return value to multiple variables:

def f(x):
    return 46, x + 1

x = 30
y, x = f(x)
# x is now 31

In C++, the use of pointers that you bring up compensates for the fact that it's relatively difficult to return multiple values from a function. In Python, while we're still technically returning one value, it's much easier to create tuples and unpack them.

luther
  • 5,195
  • 1
  • 14
  • 24
  • 1
    This is the Pythonic way: explicit is better than implicit. If you're going to use a function to change a value use `=` and there's no confusion. – Mark Ransom Nov 19 '20 at 17:18
0

You could make your own class:

`class some_class():
   self._value = 0   
   self._access_counter = 0

 def update_value(self):
  <your code here>

 def get_value_by_ref(self):
  self._access_counter += 1
  return self._value

`

Jay C
  • 23
  • 5
  • can you please provide a little more details and/or an example to express your point. – EarthIsNotFlat Nov 19 '20 at 16:53
  • Maybe it would be better to have: `class soem_class(): self._value = 0 self._value_access = 0 def update_value(self): def get_value_by_pointer(self): self._value_access += 1 return self._value ` `` – Jay C Nov 19 '20 at 17:14