0

I would like to pass a variable to an other function and in that function change the value of it.

Here is an example of the problem:

class TestClass:
    _g_a: int
    _g_b: int

    def __init__(self):
        self._g_a = 0
        self._g_b = 0

    @property
    def g_a(self):
        return self._g_a

    @g_a.setter
    def g_a(self, value):
        self._g_a = value

    @property
    def g_b(self):
        return self._g_b

    @g_b.setter
    def g_b(self, value):
        self._g_b = value

    def run(self):
        self.do_something(self.g_a, True)
        self.do_something(self.g_b, False)
        self.print_it()

    def do_something(self, the_variable, change: bool):
        if change:
            the_variable = 1

    def print_it(self):
        print(self.g_a)
        print(self.g_b)


if __name__ == '__main__':
    t = TestClass()
    t.run()

If I run the aboce code I got 0,0 as a result instead of 1,0.

In PHP there is a way to pass the reference but I don't know how to achive this in Python since I just started to work with it, and I would like to understand how can I achive such a task.

Thanks for your help!

David

Edited:

from typing import List


class TestClass:
    a: List
    b: List

    def __init__(self):
        self.a = [0]
        self.b = [0]

    def run(self):
        self.do_something(self.a, True)
        self.do_something(self.b, False)
        self.print_it()

    def do_something(self, the_variable, change: bool):
        if change:
            the_variable[0] = 1

    def print_it(self):
        print(self.a[0])
        print(self.b[0])


if __name__ == '__main__':
    t = TestClass()
    t.run()

Wathfea
  • 93
  • 2
  • 9
  • 1
    Why use a class with `property`s and `setter`s to demonstrate the problem? This could've been done with 3-4 short lines of code. The rest just serves as noise. – Axe319 Dec 07 '22 at 17:29
  • 1
    @Axe319 thanks for the constructive comment! – Wathfea Dec 07 '22 at 17:40
  • It appears that the edited version is a solution. Is that correct? Do you understand how name binding works in python? – Carl_M Dec 07 '22 at 19:41
  • @Carl_M hey, yes now I have a better perspective to it. Thanks – Wathfea Dec 08 '22 at 08:24

2 Answers2

0

Within defineAList(), assign certain values into the list; then pass the new list back into main()

-2

#Method1-using return value inside another function def fun1(a): res = a + 1 return res def fun2(c): res = c * 2 return res output = fun1(fun2(1)) print(output) #Method 2: directly calling one function in the other def function_1(n): v = n * n num = function_2(v) return num def function_2(a_number): a_number = a_number * 2 return a_number print(function_1(10))

Anjali
  • 1