파이썬

[python] 참조로 변수를 전달하려면 어떻게 해야 합니까?

zooheon 2022. 8. 21. 23:11
반응형

매개변수가 참조로 전달됩니까 아니면 값으로 전달됩니까? 'Changed'대신 아래 코드가 출력되도록 참조로 전달하려면 어떻게 해야 'Original'합니까?

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

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

 

인수는 할당에 의해 전달됩니다 . 이에 대한 근거는 두 가지입니다.

  1. 전달된 매개변수는 실제로 객체에 대한 참조 입니다(그러나 참조는 값으로 전달됨)
  2. 일부 데이터 유형은 변경 가능하지만 다른 데이터 유형은 변경 가능하지 않습니다.

그래서:

  • 변경 가능한 객체를 메소드에 전달 하면 메소드는 동일한 객체에 대한 참조를 가져오고 원하는 대로 변경할 수 있지만 메소드에서 참조를 리바인드하면 외부 범위는 그것에 대해 아무것도 알지 못합니다. 완료되면 외부 참조는 여전히 원래 개체를 가리킵니다.

  • 변경할 수 없는 개체를 메서드에 전달 하면 여전히 외부 참조를 다시 바인딩할 수 없으며 개체를 변경할 수도 없습니다.

좀 더 명확하게 하기 위해 몇 가지 예를 들어보겠습니다.

목록 - 변경 가능한 유형

메서드에 전달된 목록을 수정해 보겠습니다.

def try_to_change_list_contents(the_list):
    print('got', the_list)
    the_list.append('four')
    print('changed to', the_list)

outer_list = ['one', 'two', 'three']

print('before, outer_list =', outer_list)
try_to_change_list_contents(outer_list)
print('after, outer_list =', outer_list)

산출:

before, outer_list = ['one', 'two', 'three']
got ['one', 'two', 'three']
changed to ['one', 'two', 'three', 'four']
after, outer_list = ['one', 'two', 'three', 'four']

전달된 매개변수는 outer_list복사본이 아니라 에 대한 참조이므로 변경 목록 메서드를 사용하여 변경하고 변경 사항을 외부 범위에 반영할 수 있습니다.

이제 매개변수로 전달된 참조를 변경하려고 할 때 어떤 일이 발생하는지 살펴보겠습니다.

def try_to_change_list_reference(the_list):
    print('got', the_list)
    the_list = ['and', 'we', 'can', 'not', 'lie']
    print('set to', the_list)

outer_list = ['we', 'like', 'proper', 'English']

print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)

산출:

before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']

매개변수 는 the_list값으로 전달되었으므로 새 목록을 할당해도 메서드 외부의 코드가 볼 수 있는 효과는 없습니다. 참조 the_list사본이었고 새로운 목록을 가리켰지만 가리키는 곳을 변경할 수 있는 방법이 없었습니다 .outer_listthe_listouter_list

문자열 - 변경할 수 없는 유형

변경할 수 없으므로 문자열의 내용을 변경하기 위해 할 수 있는 일은 없습니다.

이제 참조를 변경해 보겠습니다.

def try_to_change_string_reference(the_string):
    print('got', the_string)
    the_string = 'In a kingdom by the sea'
    print('set to', the_string)

outer_string = 'It was many and many a year ago'

print('before, outer_string =', outer_string)
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)

산출:

before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago

다시 말하지만, the_string매개변수는 값으로 전달되었기 때문에 새 문자열을 할당해도 메서드 외부의 코드가 볼 수 있는 효과는 없습니다. 참조 the_string복사본이었고 새 문자열을 가리켰지만 가리키는 곳을 변경할 수 있는 방법이 없었습니다 .outer_stringthe_stringouter_string

이 문제가 조금 해결되기를 바랍니다.

편집: 이것은 @David가 원래 "실제 참조로 변수를 전달하기 위해 할 수 있는 일이 있습니까?"라는 질문에 대답하지 않는다는 점에 주목했습니다. 작업해 보겠습니다.

이 문제를 해결하려면 어떻게 해야 합니까?

@Andrea의 답변에서 알 수 있듯이 새 값을 반환할 수 있습니다. 이것은 전달되는 방식을 변경하지 않지만 다시 원하는 정보를 얻을 수 있습니다.

def return_a_whole_new_string(the_string):
    new_string = something_to_do_with_the_old_string(the_string)
    return new_string

# then you could call it like
my_string = return_a_whole_new_string(my_string)

반환 값을 사용하지 않으려면 값을 보유하고 함수에 전달하거나 목록과 같은 기존 클래스를 사용할 클래스를 만들 수 있습니다.

def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):
    new_string = something_to_do_with_the_old_string(stuff_to_change[0])
    stuff_to_change[0] = new_string

# then you could call it like
wrapper = [my_string]
use_a_wrapper_to_simulate_pass_by_reference(wrapper)

do_something_with(wrapper[0])

이것이 조금 번거로워 보이지만.

 

문제는 파이썬에 어떤 변수가 있는지에 대한 오해에서 비롯됩니다. 대부분의 전통적인 언어에 익숙하다면 다음 순서로 일어나는 일에 대한 정신적 모델이 있습니다.

a = 1
a = 2

당신은 그것이 a값을 저장하는 메모리 위치라고 생각하고 값 1을 저장하도록 업데이트됩니다 2. 그것은 파이썬에서 작동하는 방식이 아닙니다. 오히려 a값이 있는 객체에 대한 참조로 시작한 다음 값이 있는 1객체에 대한 참조로 재할당됩니다 2. a이 두 객체는 ​​더 이상 첫 번째 객체를 참조하지 않더라도 계속 공존할 수 있습니다 . 사실 그것들은 프로그램 내의 많은 다른 참조들에 의해 공유될 수 있습니다.

매개변수를 사용하여 함수를 호출하면 전달된 개체를 참조하는 새 참조가 생성됩니다. 이것은 함수 호출에 사용된 참조와 별개이므로 해당 참조를 업데이트하고 참조하도록 할 방법이 없습니다. 새 개체. 귀하의 예에서 :

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

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

self.variable문자열 개체에 대한 참조 'Original'입니다. 호출 하면 객체에 Change대한 두 번째 참조가 생성 됩니다. var함수 내에서 참조 var를 다른 문자열 객체에 재할당 'Changed'하지만 참조 self.variable는 분리되어 변경되지 않습니다.

이 문제를 해결하는 유일한 방법은 가변 객체를 전달하는 것입니다. 두 참조가 모두 동일한 개체를 참조하기 때문에 개체에 대한 모든 변경 사항은 두 위치에 모두 반영됩니다.

def __init__(self):         
    self.variable = ['Original']
    self.Change(self.variable)

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

 

다른 답변은 다소 길고 복잡하므로 Python이 변수와 매개변수를 처리하는 방식을 설명하기 위해 이 간단한 다이어그램을 만들었습니다. 여기에 이미지 설명 입력

 

반응형