How to pass arguments by reference in Python?

2

When I studied Pascal I remember that my teacher explained that to pass an argument by reference it was necessary to put var in front of the variable in the function / procedure parameters.

Example:

function exemplo(var, a: real):real;

In Python what do I need to do to make this happen?

The idea is to have a variable defined at the beginning of the program, to change it inside the function, and to change its value outside the function without using return .

    
asked by anonymous 14.11.2017 / 19:54

2 answers

1

Python works just like all languages, everything goes by value. What is different is that some values are accessed directly and others through a reference, that is, objects that are already placed in Python's internal structure and have objects that are referenced by a value in the internal Python framework. / p>

If this internal structure is accessed by a reference is an implementation details and makes no difference to you programmer.

So certain values that have semantics by value can not be passed directly by reference since the language does not provide syntax for this. It offers more complex types that are always by reference. Objects are generally so, lists and tuples as well, so encapsulate in a more complex object and it is solved. See:

def value(x):
    x = 1
def ref(x):
    x[0] = 1
x = 0
value(x)
print(x)
x = [0]
ref(x)
print(x[0])

See running on ideone . And on Coding Ground . Also I put GitHub for future reference .

    
14.11.2017 / 20:23
0

If you want to change global variables with immutable objects within the scope of a function, you must use the word global to refer to the global object. Example:

def exemplo_imutavel():
    global x
    x = 20


x = 10
exemplo()

print(x)  # 20

In case of variables with changeable objects (lists, set, dictionaries, etc.), the manipulation can be done through parameters in a simple and direct way without the use of the reserved word global . Example:

def exemplo_mutavel(x):
    x[0] = 10


x = [1, 2, 3]
exemplo(x)

print(x)  # [10, 2, 3]
    
14.11.2017 / 20:02