The language features Python 1: passing arguments to functions

Question : In Python documentation does not seem clear that a function is passed as a parameter passed by value or reference. The following code "Original Value" is changed not released:

class PassByReference:
    def __init__(self):
        self.variable = 'Original'
        self.Change(self.variable)
        print self.variable

    def Change(self, var):
        var = 'Changed'

So how to pass a value passed by reference it?
The original address : http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference
------

In Python, all variables can be understood as "reference" in memory of an object, or can also be seen in the C language void*perception.

Keep in mind that the type belongs to the object, rather than a variable. There are two variables - can be changed (mutable) and unchangeable (immutable). In Python, string, tuple, number is the object can not be changed, list, dict and so it can be modified objects.

When passed a reference to the function will automatically copy references, references in this function and outside references are not related. So like the following two examples:

a = 1
def fun(a):
    a = 2
fun(a)
print a #结果为1
a = []
def fun(a):
    a.append(1)
fun(a)
print a #结果为[1]

The first example of the function of a reference point to an immutable object when the function returns, the outside reference will not change. The second example is not the same, just inside the reference variable is the object function, and on operation of his address as a pointer positioned on an object has been modified to change the address in memory.

Reproduced in: https: //www.cnblogs.com/taceywong/p/5812967.html

Guess you like

Origin blog.csdn.net/weixin_34270606/article/details/94197936