Skip to content

Instantly share code, notes, and snippets.

@swdream
Last active September 10, 2018 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swdream/b0495124249719ec99b0d02725220067 to your computer and use it in GitHub Desktop.
Save swdream/b0495124249719ec99b0d02725220067 to your computer and use it in GitHub Desktop.

Boolean

  • True

  • False

  • and or not

List

Variables

  • global variables
  • local variables

Global variables

  • là các biến dc định nghĩa bên ngoài các function/class và chúng có thể được sử dụng bên ngoài hoặc bên trong các function/class

Local variables

  • là các variables được định nghĩa trong các fuction/class và chúng CHỈ ĐƯỢC sử dụng BÊN TRONG các function/class

Note:

  • khi một biến global A giá trị B được khai báo lại trong một function với giá trị C. Khi gọi function, biến A có giá trị C. Bên ngoài function đó, A vẫn có giá trị B

  • Nếu trong function muốn gán lại giá trị cho A thì cần sử dụng keyword global.

Yeild, Khi nào dùng yeild thay cho return

Sử dụng yeild khi muốn lặp (iterate) qua một chuỗi và không ghi value vào memory.

In [1]: def simpleGeneratorFun():
   ...:     yield 1
   ...:     yield 2
   ...:     yield 3
   ...:     

In [2]: for value in simpleGeneratorFun(): 
   ...:     print(value)
   ...:     print(value)
   ...:     
1
1
2
2
3
3

In [5]: for value in A:
   ...:     print(value)
   ...:     
1
2
3

In [6]: for value in A:
   ...:     print(value)
   ...:     

iteration

Có hàm iter

iterator

là một iterable object trong python, nghĩa là chúng ta có thể duyệt qua từng phần tử trong iterator. Chú ý là các phần tử này chỉ được duyện qua một lần và không thể duyệt qua lần thứ 2

Generator

is a simple way to create iterator, là một hàm mà kết quả trả về là một chuỗi các kết quả chứ không p là một kết quả duy nhất. Các kết quả này chỉ được duyệt qua một lần duy nhất, sử dụng yeild thay cho return.

( i for i in range(5)) => tạo ra môt generator

decorator

là một callable object, dùng để modify các function hoặc class

Callable objects are objects which accepts some arguments and returns some objects.

Decorator function là các function nhận function khác như các arguments, add wapper around them và return lại một function khác với wapper

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

def say_whee():
    print("Whee!")

say_whee = my_decorator(say_whee)

Truyền args

  • *args nhận các tham số truyền bình thường. Sử dụng args như một list.
  • **kwargs nhận tham số truyền theo tên. Sử dụng kwargs như một. dictionary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment