Passing an integer by reference in Python

后端 未结 11 1873
天命终不由人
天命终不由人 2020-11-22 12:29

How can I pass an integer by reference in Python?

I want to modify the value of a variable that I am passing to the function. I have read that everything in Python i

11条回答
  •  执念已碎
    2020-11-22 12:47

    Not exactly passing a value directly, but using it as if it was passed.

    x = 7
    def my_method():
        nonlocal x
        x += 1
    my_method()
    print(x) # 8
    

    Caveats:

    • nonlocal was introduced in python 3
    • If the enclosing scope is the global one, use global instead of nonlocal.

提交回复
热议问题