Metodlarni dekoratsiyalash
Ahamiyatli jihatlaridan biri shundaki, Pythondagi funksiya va metodlarning har doim birinchi para-metr sifatida obyektning o‘ziga (self) havola kiritishi hisobga olinmasa, bir-biridan farq qilmaydi. Demak, biz metodlar uchun ham xuddi funksiyalar kabi (faqat self i esdan chiqarmagan holda) dekoratorlar yaratishimiz mumkin ekan.
def method_friendly_decorator(method_to_decorate): def wrapper(self, lie):
lie -= 3
return method_to_decorate(self, lie) return wrapper
def __init__(self):
self.age = 32
@method_friendly_decorator
def sayYourAge(self, lie):
print("Mening yoshim {}da, qancha berasiz?".format(self.age + lie))
Mening yoshim 26 da, siz qancha berasiz?
Agar biz maksimal tarzda umumiy dekorator yaratib, uning har qanday funksiya yoki metodga nisbatan qo‘llanilishini istasak, argumentlarni ochish metodidan foydalanishimiz mumkin.
def a_decorator_passing_arbitrary_arguments(function_to_decorate):
def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs): print("Menga biror narsa berib yuborishdimi?:") print(args)
print(kwargs)
function_to_decorate(*args, **kwargs) return a_wrapper_accepting_arbitrary_arguments
@a_decorator_passing_arbitrary_arguments def function_with_no_argument(): print("Python is cool, no argument here.")
function_with_no_argument()
Menga biror narsa berib yuborishdimi?:
()
{}
Python is cool, no argument here.
@a_decorator_passing_arbitrary_arguments def function_with_arguments(a, b, c):
print(a, b, c)
113
function_with_arguments(1, 2, 3) Menga biror narsa berib yuborishdimi?: (1, 2, 3)
{}
1 2 3
@a_decorator_passing_arbitrary_arguments
def function_with_named_arguments(a, b, c, platypus="Nimaga yo`q?"):
print("{} , {} va {} lar o`rdakburularni yoqtirishadimi? {} ".
format(a, b, c, platypus))
function_with_named_arguments("Bill", "Linus", "Stiv", platypus="Aniq ha!") Menga biror narsa berib yuborishmadimi?:
('Bill', 'Linus', 'Stiv') {'platypus': Aniq ha!'}
Bill, Linus va Stiv o`rdakburunlarni yoqtirishadimi? Aniq ha!
def __init__(self):
self.age = 31
@a_decorator_passing_arbitrary_arguments
def sayYourAge(self, lie=-3): # Endi biz odatiy qiymatni ko`rsata olamiz print("Mening yoshim {} da, Siz qancha berasiz?".format(self.
age + lie))
Menga biror narsa berib yuborishmadimi?
(<__main__.Mary object at 0x7f6373017780>,)
{}
Mening yoshim 28 da, siz qancha berasiz?
Do'stlaringiz bilan baham: |