How do I pass a variable by reference

0 votes

How to passed by reference or value, and the following code produces the unchanged value 'Original'

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

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

Is there something I can do to pass the variable by actual reference?

Nov 18, 2020 in Python by kartik
• 37,510 points
47 views

1 answer to this question.

0 votes

Hello,

Just wrap it in a list:

def Change(self, var):
    var[0] = 'Changed'

variable = ['Original']
self.Change(variable)      
print variable[0]
answered Nov 18, 2020 by Niroj
• 82,720 points

Related Questions In Python

0 votes
1 answer

How do I sort a dictionary by value?

It is not possible to sort a ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 58,120 points
176 views
0 votes
2 answers

In Python, how do I read a file line-by-line into a list?

readline function help to  read line in ...READ MORE

answered Jun 21, 2020 in Python by sahil
• 540 points
474 views
0 votes
1 answer

How do I sort a dictionary by value?

If you construct a dictionary with the ...READ MORE

answered Mar 12, 2019 in Python by Trisha
119 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,033 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
1,556 views
0 votes
1 answer

How do I sort a list of dictionaries by a value of the dictionary?

Hello @kartik, import operator To sort the list of ...READ MORE

answered Apr 23, 2020 in Python by Niroj
• 82,720 points
130 views
0 votes
1 answer

How do I detect whether a Python variable is a function?

Hello @kartik, You can import isfunction from the inspect module. >>> from inspect ...READ MORE

answered Dec 7, 2020 in Python by Niroj
• 82,720 points
51 views