Menulis Function di Python
Shayne Miel
Software Architect @ Duo Security
def foo():
a = 5
def bar():
print(a)
return bar
func = foo()
func()
5
Klosur!
type(func.__closure__)
<class 'tuple'>
len(func.__closure__)
1
func.__closure__[0].cell_contents
5
x = 25
def foo(value):
def bar():
print(value)
return bar
my_func = foo(x)
my_func()
25
del(x)
my_func()
25
len(my_func.__closure__)
1
my_func.__closure__[0].cell_contents
25
x = 25
def foo(value):
def bar():
print(value)
return bar
x = foo(x)
x()
25
len(x.__closure__)
1
x.__closure__[0].cell_contents
25
Fungsi bersarang: Fungsi yang didefinisikan di dalam fungsi lain.
# outer function
def parent():
# nested function
def child():
pass
return child
Variabel nonlokal: Variabel pada fungsi induk yang dipakai fungsi anak.
def parent(arg_1, arg_2):
# Dari sudut pandang child(),
# `value` dan `my_dict` adalah variabel nonlokal,
# begitu juga `arg_1` dan `arg_2`.
value = 22
my_dict = {'chocolate': 'yummy'}
def child():
print(2 * value)
print(my_dict['chocolate'])
print(arg_1 + arg_2)
return child
Klosur: Variabel nonlokal yang melekat pada fungsi yang dikembalikan.
def parent(arg_1, arg_2):
value = 22
my_dict = {'chocolate': 'yummy'}
def child():
print(2 * value)
print(my_dict['chocolate'])
print(arg_1 + arg_2)
return child
new_function = parent(3, 4)
print([cell.cell_contents for cell in new_function.__closure__])
[3, 4, 22, {'chocolate': 'yummy'}]
Decorator menggunakan:
Menulis Function di Python