Skip to content

Instantly share code, notes, and snippets.

@bluzky
Last active August 29, 2015 14:23
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 bluzky/7c86b5f1c257b2896c20 to your computer and use it in GitHub Desktop.
Save bluzky/7c86b5f1c257b2896c20 to your computer and use it in GitHub Desktop.
Python decorator introduction
__author__ = 'bluzky'
def name_decorator(f):
def wrapper(ten):
chuoi_moi = "Ten tui la %s" % ten
return f(chuoi_moi)
return wrapper
# su dung decorator
@name_decorator
def xuat_ten(ten):
print ten
xuat_ten('Coulson')
# khong su dung decorator
def xuat_ten_2(ten):
print ten
ham_xuat_ten_moi = name_decorator(xuat_ten_2)
ham_xuat_ten_moi('Coulson')
def chuc_danh_decorator(ten_chuc_danh):
def ten_decorator(f):
def wrapper(ten):
chuoi_moi = "Xin gioi thieu %s %s" % (ten_chuc_danh, ten)
return f(chuoi_moi)
return wrapper
return ten_decorator
@chuc_danh_decorator("Giao su")
def gioi_thieu(ten):
print ten
@chuc_danh_decorator("Tien si")
def gioi_thieu_2(ten):
print ten
gioi_thieu("Teo") #Xin gioi thieu Giao su Ti
gioi_thieu_2("Ti") #Xin gioi thieu Tien si Teo
from functools import wraps
def ten_decorator(f):
@wraps(f)
def wrapper(ten):
chuoi_moi = "Ten tui la %s" % ten
return f(chuoi_moi)
return wrapper
def xuat_ten( ten ):
print ten
print xuat_ten.__name__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment