वास्तविक दुनिया के उदाहरण

Python में Functions लिखना

Shayne Miel

Software Architect @ Duo Security

किसी फ़ंक्शन का समय नापें

import time

def timer(func):
  """एक डेकोरेटर जो बताता है कि फ़ंक्शन चलने में कितना समय लगा.

  Args:
    func (callable): जिस फ़ंक्शन को डेकोरेट किया जा रहा है.

  Returns:
    callable: डेकोरेट किया हुआ फ़ंक्शन.
  """
Python में Functions लिखना
import time

def timer(func):
  """एक डेकोरेटर जो बताता है कि फ़ंक्शन चलने में कितना समय लगा."""

# लौटाने के लिए wrapper फ़ंक्शन परिभाषित करें. def wrapper(*args, **kwargs):
# wrapper() कॉल होने पर, current time लें. t_start = time.time()
# डेकोरेटेड फ़ंक्शन कॉल करें और परिणाम रखें. result = func(*args, **kwargs)
# कुल लगा समय निकालें और प्रिंट करें. t_total = time.time() - t_start print('{} took {}s'.format(func.__name__, t_total))
return result
return wrapper
Python में Functions लिखना

timer() का उपयोग

@timer
def sleep_n_seconds(n):
  time.sleep(n)
sleep_n_seconds(5)
sleep_n_seconds took 5.0050950050354s
sleep_n_seconds(10)
sleep_n_seconds took 10.010067701339722s
Python में Functions लिखना
def memoize(func):
  """डेकोरेटेड फ़ंक्शन के परिणाम तेज़ lookup के लिए स्टोर करें
  """

# परिणामों को एक dict में रखें जो arguments को results से मैप करता है cache = {}
# लौटाने के लिए wrapper फ़ंक्शन परिभाषित करें. def wrapper(*args, **kwargs): # 'kwargs' के लिए hashable key बनाएँ. kwargs_key = tuple(sorted(kwargs.items()))
# अगर ये arguments पहले नहीं देखे गए हैं, if (args, kwargs_key) not in cache:
# func() कॉल करें और परिणाम स्टोर करें. cache[(args, kwargs_key)] = func(*args, **kwargs)
return cache[(args, kwargs_key)]
return wrapper
Python में Functions लिखना
@memoize
def slow_function(a, b):
  print('Sleeping...')
  time.sleep(5)
  return a + b
slow_function(3, 4)
Sleeping...

7
slow_function(3, 4)
7
Python में Functions लिखना

डेकोरेटर्स कब इस्तेमाल करें

  • कई फ़ंक्शनों में common behavior जोड़ें
@timer
def foo():
  # do some computation

@timer
def bar():
  # do some other computation

@timer
def baz():
  # do something else
Python में Functions लिखना

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

Python में Functions लिखना

Preparing Video For Download...