Closures

Python में Functions लिखना

Shayne Miel

Software Architect @ Duo Security

नैस्टेड फंक्शन पर nonlocal वैरिएबल जोड़ना

def foo():
  a = 5
  def bar():
    print(a)
  return bar

func = foo()

func()
5

Closures!

type(func.__closure__)
<class 'tuple'>
len(func.__closure__)
1
func.__closure__[0].cell_contents
5
Python में Functions लिखना

Closures और deletion

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
Python में Functions लिखना

Closures और overwriting

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
Python में Functions लिखना

परिभाषाएँ - nested function

Nested function: एक फंक्शन जो किसी दूसरे फंक्शन के अंदर defined हो।

# outer function
def parent():
  # nested function
  def child():
    pass
  return child
Python में Functions लिखना

परिभाषाएँ - nonlocal variables

Nonlocal variables: वे वैरिएबल जो parent फंक्शन में defined हों और child फंक्शन में use हों।

def parent(arg_1, arg_2):
  # child() के नज़रिए से
  # `value` और `my_dict` nonlocal variables हैं,
  # जैसे `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
Python में Functions लिखना

Closure: nonlocal variables जो return की गई फंक्शन से जुड़े हों।

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'}]
Python में Functions लिखना

यह सब क्यों मायने रखता है?

Decorators उपयोग करते हैं:

  • Functions as objects
  • Nested functions
  • Nonlocal scope
  • Closures
Python में Functions लिखना

अभ्यास करते हैं!

Python में Functions लिखना

Preparing Video For Download...