Temat 3: Funkcje, dekoratory i moduły

Wstecz; Ostatnia modyfikacja: 24.04.2015
  • Zadania powtórzeniowe na rozgrzewkę
  • Ćw 1: co wypisze poniższy program?
  • def funkcja(x,y,*args):
        return args
    print(funkcja(*funkcja(1,2,3,4,5))[0])
    
  • Ćw 2: jaki będzie wynik poniższych operacji?
  • x=[1,2]
    def funkcja(y):
        global x
        x.append(y[x[0]])
    funkcja(x)
    print(x)
    
  • przetestuj: globals(), locals()
  • Ćw 3: napisz funkcję gwiazda(N), która wypisuje taką gwiazdę:
  • &....&....&
    .&...&...&.
    ..&..&..&..
    ...&.&.&...
    ....&&&....
    &&&&&&&&&&&
    ....&&&....
    ...&.&.&...
    ..&..&..&..
    .&...&...&.
    &....&....&
    
  • dekoratory (funkcje wyższych rzędów)
  • def cache(fun):
      def res_fun(*args):
        if res_fun.mem.has_key(args):
          return res_fun.mem[args]
        else:
          result = fun(*args)
          res_fun.mem[args] = result  # zapamiętujemy wynik
          return result
      res_fun.mem = {}
      res_fun.__name__ = fun.__name__
      res_fun.__doc__ = fun.__doc__
      res_fun.__dict__.update(fun.__dict__)
      return res_fun      # zwracamy funkcję opakowaną w spamiętywanie
    
    @cache
    def fib(n):
      if n<=1:
        return n
      else:
        return fib(n-1) + fib(n-2)
    
  • dekorator: logowanie wywołań
  • def logged(fun):
      def res_fun(*args, **kwargs):
         print(" "*(res_fun.d)+res_fun.__name__+" invoked: " + str(args))
         res_fun.d += 1       # zwiększamy poziom zaglębienia rekurencji (opcjonalne)
         res = fun(*args, **kwargs)
         res_fun.d -= 1       # zmniejszamy poziom zaglębienia rekurencji (opcjonalne)
         print(" "*(res_fun.d) +res_fun.__name__+ " returned: " + str(res))
         return res
      res_fun.d = 0
      res_fun.__name__ = fun.__name__
      res_fun.__doc__ = fun.__doc__
      res_fun.__dict__.update(fun.__dict__)
      return res_fun
    
    @logged
    @cache
    def fib(n):
      if n<=1:
        return n
      else:
        return fib(n-1) + fib(n-2)
    
  • Ćw 4: napisz dekoratory: deprecated i count
  • importowanie modułów
  • import numpy
    import numpy as np
    dir(np)
    import math
    dir(math)
    from math import *
    
  • komentowanie modułów (docstringi)
  • """
    Assuming this is file mymodule.py, then this string, being the
    first statement in the file, will become the "mymodule" module's
    docstring when the file is imported.
    """
     
    class MyClass(object):
        """The class's docstring"""
     
        def my_method(self):
            """The method's docstring"""
     
     
    def my_function():
        """The function's docstring"""
    
  • Ćw 4: zaimplementuj program do liczenia słów w tekście jako moduł o nazwie atext. Napisz krótkie komentarze (docstringi). Zaimplementuj następujące funkcje:
  • def readtxt(input_fn) # zwraca tekst
    def words(text)            # zwraca listę słów
    def word_counts(ws)        # zwraca zbiór słów wraz z ilością wystąpień
    def sentences(text)        # zwraca listę zdań
    
  • Opcjonalnie: programowanie obiektowe - (Ćw 5): zaprojektuj i zaimplementuj grę w kółko i krzyżyk
  • Ćwiczenia: ćwiczenia ze skryptu 2
  • Kod z ćwiczeń