Last active
August 29, 2015 14:23
-
-
Save bluzky/7c86b5f1c257b2896c20 to your computer and use it in GitHub Desktop.
Python decorator introduction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__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') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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