Door toewijzing doorgeven

Functies schrijven in Python

Shayne Miel

Software Architect @ Duo Security

Een verrassend voorbeeld

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
Functies schrijven in Python

Dieper duiken

RAM

Functies schrijven in Python

Dieper duiken

a = [1, 2, 3]

a instellen

Functies schrijven in Python

Dieper duiken

a = [1, 2, 3]

b = a

b is a

Functies schrijven in Python

Dieper duiken

a = [1, 2, 3]

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

toevoegen aan a

Functies schrijven in Python

Dieper duiken

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]

toevoegen aan b

Functies schrijven in Python

Dieper duiken

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 is 42

Functies schrijven in Python

Door toewijzing doorgeven

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

RAM

Functies schrijven in Python

Door toewijzing doorgeven

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

my_list = [1, 2, 3]

my_list instellen

Functies schrijven in Python

Door toewijzing doorgeven

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

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

foo() aanroepen

Functies schrijven in Python

Door toewijzing doorgeven

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

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

x en my_list bijwerken

Functies schrijven in Python

Door toewijzing doorgeven

def bar(x):
  x = x + 90

my_var = 3

my_var

Functies schrijven in Python

Door toewijzing doorgeven

def bar(x):
  x = x + 90

my_var = 3
bar(my_var)

bar() aanroepen

Functies schrijven in Python

Door toewijzing doorgeven

def bar(x):
  x = x + 90

my_var = 3
bar(my_var)
my_var
3

x aan iets nieuws toewijzen

Functies schrijven in Python

Onveranderlijk of veranderlijk?

Onveranderlijk

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

Veranderlijk

  • list
  • dict
  • set
  • bytearray
  • objecten
  • functies
  • bijna alles andere!
Functies schrijven in Python

Veranderlijke standaardargumenten zijn riskant!

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]
Functies schrijven in Python

Laten we oefenen!

Functies schrijven in Python

Preparing Video For Download...