[Python] How do I pass a variable by reference?

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I wrote this class for testing:

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

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


    When I tried creating an instance, the output was Original. So it seems like parameters in Python are passed by value. Is that correct? How can I modify the code to get the effect of pass-by-reference, so that the output is Changed?


    Sometimes people are surprised that code like x = 1, where x is a parameter name, doesn't impact on the caller's argument, but code like x[0] = 1 does. This happens because item assignment and slice assignment are ways to mutate an existing object, rather than reassign a variable, despite the = syntax. See Why can a function modify some arguments as perceived by the caller, but not others? for details.

    See also What's the difference between passing by reference vs. passing by value? for important, language-agnostic terminology discussion.

    Continue reading...

Compartilhe esta Página