Python Properties

Python Decorators haqida o'rganamiz.

SU

Python Property-lari

Python property-lari, sinf funktsiyasini atributga aylantirish usulini taqdim etadi. Shuningdek, ular getter va setter yordamida Python'da maxfiy atribut yaratishga imkon beradi. Python haqiqatan ham maxfiy metodlar va atributlarga ega emas, chunki bitta yoki ikki pastki chiziq bilan boshlanadigan elementlarga hali ham kirish mumkin. Ammo, odat bo'yicha, agar siz instansiya o'zgaruvchisi yoki metodini bitta yoki ikki pastki chiziq bilan boshlasangiz, bu ularni maxfiy deb hisoblashadi. Agar siz bunday o'zgaruvchilar va metodlardan foydalansangiz, kodingiz yangi versiyalar chiqarilganda o'zgaruvchilar yoki metodlar o'zgarganida yoki yo'qolganida ishlamay qolishi mumkin.

"Getter" — bu maxfiy atributga bilvosita kirish uchun ishlatiladigan funktsiya, "setter" esa maxfiy atributni o'rnatish uchun ishlatiladigan funktsiyadir. Python bu tushunchaga ega emas, chunki ko'plab hollarda atributlarga bevosita kirish va o'zgartirish mumkin.

Keling, o'z getter va setter metodlarini yaratib, sinf yaratishni boshlaylik:

class Amount:
 
    def __init__(self):
        # maxfiy atribut
        self._amount = None
 
    def get_amount(self):
        return self._amount
 
    def set_amount(self, value):
        if isinstance(value, int) or isinstance(value, float):
            self._amount = value
        else:
            print(f'Value must be an int or float')
 
if __name__ == '__main__':
    amt = Amount()
    print(f'The current amount is {amt.get_amount()}')
    amt.set_amount('the')
    print(f'The current amount is {amt.get_amount()}')
    amt.set_amount(5.5)
    print(f'The current amount is {amt.get_amount()}')

Ushbu misolda, siz self._amount o'zgaruvchisini maxfiy qilib yaratdingiz va uni None ga o'rnatyapsiz. Bu qiymatni olish uchun get_amount() metodini yaratdingiz. Keyin, set_amount() metodini yaratib, qiymatni o'rnatish uchun uni ishlatdingiz. set_amount() metodi sizga asosiy xatolik tekshiruvini amalga oshirishni ham ta'minlaydi.

Kodni ishga tushirganda quyidagi natijani ko'rasiz:

The current amount is None
Value must be an int or float
The current amount is None
The current amount is 5.5

Python bu jarayonni osonlashtiradi, chunki getter va setter metodlarini property ga aylantirish imkonini beradi.

Keling, kodni oxirgi qatorda bitta qator qo'shib yangilaymiz:

class Amount:
 
    def __init__(self):
        # maxfiy atribut
        self._amount = None
 
    def get_amount(self):
        return self._amount
 
    def set_amount(self, value):
        if isinstance(value, int) or isinstance(value, float):
            self._amount = value
        else:
            print(f'Value must be an int or float')
 
    amount = property(get_amount, set_amount)
 
if __name__ == '__main__':
    amt = Amount()
    print(f'The current amount is {amt.amount}')
    amt.amount = 'the'
    print(f'The current amount is {amt.amount}')
    amt.amount = 5.5
    print(f'The current amount is {amt.amount}')

Bu yerda siz Python'ga Amount sinfiga yangi property yoki atribut qo'shishni xohlayotganingizni aytib berasiz. Siz uni property funktsiyasini ishlatib yaratdingiz, bu setter, getter va delete metodlarini qabul qiladi, ammo bu holatda delete metodini e'tiborsiz qoldirdik.

Endi siz get_amount() va set_amount() metodlarini chaqirish o'rniga, bevosita amount atributiga kirish va o'rnatish mumkin.

Bundan ham osonroq usul sifatida property dekoratorini ishlatish mumkin.

Keling, kodni dekorator sintaksisi bilan yangilaymiz:

class Amount:
 
    def __init__(self):
        # maxfiy atribut
        self._amount = None
 
    @property
    def amount(self):
        return self._amount
 
    @amount.setter
    def amount(self, value):
        if isinstance(value, int) or isinstance(value, float):
            self._amount = value
        else:
            print(f'Value must be an int or float')
 
if __name__ == '__main__':
    amt = Amount()
    print(f'The current amount is {amt.amount}')
    amt.amount = 'the'
    print(f'The current amount is {amt.amount}')
    amt.amount = 5.5
    print(f'The current amount is {amt.amount}')

Bu safar siz get_amount() metodini amount() metodiga aylantirib, uni @property bilan bezadingiz. Keyin, uning setterini yaratish uchun ikkinchi amount() metodini yaratdingiz, lekin uni amount.setter bilan bezadingiz. Kod bir oz g'alati ko'rinishi mumkin, ammo ishlaydi. O'zingiz sinab ko'ring!

Property dekoratorining juda yaxshi foydasi shundaki, siz sinfni oddiy atributlar bilan yaratishingiz mumkin va keyinchalik ularni property'ga aylantirishingiz mumkin, agar siz ularni olish yoki o'rnatishda qo'shimcha qayta ishlashni kashf etsangiz.

Last updated on

On this page

Xato haqida xabar berish