指派呼叫傳遞

Python 函式寫作

Shayne Miel

Software Architect @ Duo Security

出乎意料的例子

def foo(x):
  x[0] = 99

my_list = [1, 2, 3]
foo(my_list)
print(my_list)
[99, 2, 3]
def bar(x):
  x = x + 90

my_var = 3
bar(my_var)
print(my_var)
3
Python 函式寫作

再深入一點

RAM

Python 函式寫作

再深入一點

a = [1, 2, 3]

設定 a

Python 函式寫作

再深入一點

a = [1, 2, 3]

b = a

b 等於 a

Python 函式寫作

再深入一點

a = [1, 2, 3]

b = a
a.append(4)
print(b)
[1, 2, 3, 4]

對 a 做 append

Python 函式寫作

再深入一點

a = [1, 2, 3]

b = a
a.append(4)
print(b)
[1, 2, 3, 4]
b.append(5)

print(a)
[1, 2, 3, 4, 5]

對 b 做 append

Python 函式寫作

再深入一點

a = [1, 2, 3]

b = a
a.append(4)
print(b)
[1, 2, 3, 4]
b.append(5)

print(a)
[1, 2, 3, 4, 5]
a = 42

a 等於 42

Python 函式寫作

指派呼叫傳遞

def foo(x):
  x[0] = 99

RAM

Python 函式寫作

指派呼叫傳遞

def foo(x):
  x[0] = 99

my_list = [1, 2, 3]

設定 my_list

Python 函式寫作

指派呼叫傳遞

def foo(x):
  x[0] = 99

my_list = [1, 2, 3]
foo(my_list)

呼叫 foo()

Python 函式寫作

指派呼叫傳遞

def foo(x):
  x[0] = 99

my_list = [1, 2, 3]
foo(my_list)
print(my_list)
[99, 2, 3]

更新 x 與 my_list

Python 函式寫作

指派呼叫傳遞

def bar(x):
  x = x + 90

my_var = 3

my_var

Python 函式寫作

指派呼叫傳遞

def bar(x):
  x = x + 90

my_var = 3
bar(my_var)

呼叫 bar()

Python 函式寫作

指派呼叫傳遞

def bar(x):
  x = x + 90

my_var = 3
bar(my_var)
my_var
3

把 x 指派為新物件

Python 函式寫作

不可變或可變?

不可變(Immutable)

  • int
  • float
  • bool
  • string
  • bytes
  • tuple
  • frozenset
  • None

可變(Mutable)

  • list
  • dict
  • set
  • bytearray
  • 物件
  • 函式
  • 幾乎其他全部!
Python 函式寫作

可變的預設參數很危險!

def foo(var=[]):
  var.append(1)
  return var

foo()
[1]
foo()
[1, 1]
def foo(var=None):
  if var is None:
    var = []
  var.append(1)
  return var

foo()
[1]
foo()
[1]
Python 函式寫作

一起來練習吧!

Python 函式寫作

Preparing Video For Download...