Python objects by reference

Robert Heaton

Is Python pass-by-reference or pass-by-value?

“Suppose I say to Fat, or Kevin says to Fat, “You did not experience God. You merely experienced something with the qualities and aspects and nature and powers and wisdom and goodness of God.” This is like the joke about the German proclivity toward double abstractions; a German authority on English literature declares, “Hamlet was not written by Shakespeare; it was merely written by a man named Shakespeare.” In English the distinction is verbal and without meaning, although German as a language will express the difference (which accounts for some of the strange features of the German mind).”

Philip K. Dick is not known for his light or digestible prose. The vast majority of his characters are high. Like, really, really, really high. And yet, in the above quote from Valis (published in 1981), he gives a remarkably foresighted explanation of the notoriously misunderstood Python parameter passing paradigm. Plus ça change, plus c’est omnomnomnom drugs.

The two most widely known and easy to understand approaches to parameter passing amongst programming languages are pass-by-reference and pass-by-value. Unfortunately, Python is “pass-by-object-reference”, of which it is often said:

“Object references are passed by value.”

When I first read this smug and overly-pithy definition, I wanted to punch something. After removing the shards of glass from my hands and being escorted out of the strip club, I realised that all 3 paradigms can be understood in terms of how they cause the following 2 functions to behave:

Читайте также:  Python mysql sqlalchemy example

You may also want to read about the interesting interactions these concepts have with mutable and immutable types. But those are stories for another day. Now if you’ll excuse me, I’m going to read “Do Androids Dream Of Electric Sheep?” — my meta-programming is a little rusty.

More on Programming

Источник

How Call by Value and Call by Reference Work in Python?

In above example the address of varible a and b using & followed by variable name , where in function defination
* followed parameter known as pointer variable which used
to storing addresses, because of this values in varible a and b is modified.

Now we have seen what is call by value and call by reference with example

But, Python programming language uses the mechanism of the call-by-object and also call by object reference.

Each object whenever it is instantiated ,it is assigned unique id and its type if defined at runtime and id(object) returns a unique identity (integer value) of that object.

to move further into the topic first we have to understand mutable object and immutable object in python.

  • Mutable Objects
    Datatypes that can be modified or if there state can be changed those objects are known as Mutable datatype
    like (list, dictionaries, set) .
  • Immutable Objects
    Datatypes that cannot be modified or if there state cannot be changed those objects are known as Immutable datatype like **(int, float, bool, string, unicode, tuple).

So when Mutable objects are passed to the function call then it is treated as **call by value.**

And When Immutable objects are passed to the function call and there value is modified then it is treated as **call by reference.**

For the sake of simplicity we’re going to use the word call by value and call by reference instead of (call by object) and (call by object reference) respectivly.

let’s take examples for call by reference and call by value

Example :- Call by reference (with Immutable objects (int, float, bool, string) and no object state modified) in python

num1 = 43 num2 = 12.44 num3 = False name = 'hello' print("Id in main function scope") print(f"id of num1 = ") print(f"id of num2 = ") print(f"id of num2 = ") print(f"id of name = ") def call_by_reference(num1,num2,num3,name): print("\nId within function") print(f"id of num1 = ") print(f"id of num2 = ") print(f"id of num2 = ") print(f"id of name = ") call_by_reference(num1,num2,num3,name) Output :- Id in main function scope id of num1 = 94157957099328 id of num2 = 140438713493200 id of num2 = 94157956423968 id of name = 140438848940272 Id within function id of num1 = 94157957099328 id of num2 = 140438713493200 id of num2 = 94157956423968 id of name = 140438848940272 

So we can see that the id’s the objects (num1, num2, num3) has not change becuase have not applied modification to those objects.

Example :- Call by reference (with Mutable objects (list ,dict) and object state modified) in python

names = ['ram', 'shyam', 'bharat'] d = print("Id in main function scope") print(f"id of names list = ") print(f"id of d dict = ") def call_by_reference(name, d): print("Id within function") d['sam'] = 12 names.append('john') print("\nModified Objects id :-") print(f"id of names list = ") print(f"id of d dict = ") call_by_reference(names, d) print("Modfied list and dict") print(f"names = ") print(f"dict = ") Output :- Id in main function scope id of names list = 140439297460096 id of d dict = 140438712179600 Id within function Modified Objects id :- id of names list = 140439297460096 id of d dict = 140438712179600 Modfied list and dict names = ['ram', 'shyam', 'bharat', 'john'] dict =

We can see even after modifying the objects state the id’s of the object remains unchanged because the objects datatype are mutable objects here by ,even if the object state is modified
it is treated as call by reference(call by object reference).

Example :- Call by Value (with Immutable objects (int, float, bool, string) and object state modified) in python

num1 = 43 num2 = 12.44 num3 = False name = 'hello' print("Id in main function scope") print(f"id of num1 = ") print(f"id of num2 = ") print(f"id of num2 = ") print(f"id of name = ") def call_by_value(num1,num2,num3,name): print("\nId within function") num1 = 1 num2 = 2 num3 = 3 name = 'sam' print("Modified Objects id") print(f"id of num1 = ") print(f"id of num2 = ") print(f"id of num2 = ") print(f"id of name = ") call_by_value(num1,num2,num3,name) print("\Unmodified int, float, bool, string objects value in global scope") print(f'num1 = ') print(f'num2 = ') print(f'num3 = ') Output :- Id in main function scope id of num1 = 94157957099328 id of num2 = 140438713494320 id of num2 = 94157956423968 id of name = 140438848940272 Id within function Modified Objects id id of num1 = 94157957097984 id of num2 = 94157957098016 id of num2 = 94157957098048 id of name = 140438713157936 Unmodified int, float, bool, string objects value in global scope num1 = 43 num2 = 12.44 num3 = False 

In the above example we can see that after modifying the Immuatable objects the object id’s were diffrent , this is because we cannot modify the value of Immutables and because of this new 3 objects named (num1, num2, num3, name) where created in the function local scope after the function call we have also print the value to verify the objects in the global scope remain unchanged.

Example :- Call by Value (with Immutable objects (tuple) and object state modified) in python

names = ('ram', 'shyam', 'bharat') print("Id in main function scope") print(f"id of names tuple = ") def call_by_value(name, d): print("Id within function") names = ('ram','shyam','bharat','john') print(f"modified object value \n") print("\nModified Objects id :-") print(f"id of names tuple = ") call_by_value(names, d) print("\nUnchanged tuple object in global scope") print(f"names = ") Output :- Id in main function scope id of names tuple = 140438712974144 Id within function modified object value ('ram', 'shyam', 'bharat', 'john') Modified Objects id :- id of names tuple = 140438712255888 Unchanged tuple object in global scope names = ('ram', 'shyam', 'bharat') 

In the above example we can have assigned a new tuple with same elements + one more element because (tuple datatype does not support any add method) andchecked the object id which is diffrent because a new object gets created and also the global object remain unchanged because of it’s Immutable nature.

With this example we have come to an end
hope you all have understood the topics
covered in this article.

Источник

Python — pass by reference

In this tutorial, we will learn how to use pass by reference in Python. Variables work differently in Python than in any other programming language known to us. It is a memory location with a unique address whereas in Python, variables are not declared beforehand but the data decides the data type.

Table of Contents

  1. What is pass by reference
  2. Pass by reference vs value in Python
  3. Python Object Model
  4. Closing Thoughts

What is pass by reference?

Before we jump into the technical details, let’s first see what does pass and by reference actually mean.
By pass we mean to provide an argument to a function. Whereas by reference means that the argument that has been passed to the function is a reference to a variable that is already existing in the memory. Now that we have cleared that, now we can learn about pass by reference.

In pass by reference, the variable is passed into the function directly while the variable acts as a Package that comes with the objects. Because you’ve given the function a reference to an existing variable, any operations you execute on it will have a direct effect on the variable it refers to.

Pass by reference vs value in Python

When you give function parameters via reference, you’re just passing references to values that already exist. When you pass arguments by value, on the other hand, the arguments become independent copies of the original values.

Pass by value

Any other operation performed will not have any effect on the original value as the argument passed to the function is copied. It only changes the value of the copy created within the function.

Input:

def function(int): int+=100 print("Inside function call ",int) int=100 print("Before function call ",int) function(int) print("After function call ",int) 

Here, a copy of the argument is created, and changes are made to that copy such that the original value is not affected. As a result, the original value is printed after the function call.

Output:

Before function call 100 Inside function call 200 After function call 100 

In this, we assigned the variable the value ‘100’ and changed it to ‘200’, but the change was not seen outside the function i.e. int is still ‘100’. Hence proved, it is pass by value method.

Pass by reference

This method passes a reference to the original arguments, and any operation performed on the parameter affects the actual value. It alters the value in both function and globally.

Input:

def function(int): int.append('B')print("Inside function call",int) int=['A'] print("Before function call",int) function(int) print("After function call",int)

When a list is used, its reference is supplied into the function, and any modifications to the list have an effect even after the method has been called.

Output:

Before function call ['A'] Inside function call ['A', 'B'] After function call ['A', 'B']

In the above example, function() returns a string and also modifies the value of int. This shows that Python supports the pass by reference method.

Python Object Model

It’s best if we first understand what Python objects are and how to characterize them. In Python, everything is an object. Object’s identity, data type and object’s content characterize every object.

# the identity of `int` id(int) 3578332784044 # the type of `int` type(int) # the contents of `int` int [1, 2, 3] 

As we can see above, id is the built-in function you use to query the identity of an object, and type is the built-in function you use to query the type of an object.

Closing Thoughts

Python operates differently than the other programming languages when it comes to the moving of the arguments. Since you’re giving the function a reference to an existing variable, all operations performed on this reference will directly affect the variable to which it refers. One can learn about other Python-related concepts here.

Источник

Оцените статью