โฌ…๏ธ Bosh sahifaga
1 / 16

๐Ÿ“š Python OOP - 6-dars

Special Methods (Magic Methods)

__init__, __str__, __len__ va boshqalar

Assalomu alaykum, yosh dasturchilar! ๐Ÿ˜Š
Bugun biz Python'ning juda qiziqarli va kuchli xususiyati - Special Methods'ni o'rganamiz

120 daqiqa

๐Ÿ“‹ Dars rejasi

๐Ÿค” Special Methods nima?

Special Methods `__` (ikki pastki chiziq) bilan boshlanadi va tugaydi. Shuning uchun ularni "Magic Methods" deb ham atashadi.

๐Ÿ’ก Real hayotdan misol:

Agar sizda "Vaqt" class bo'lsa, siz uni `print()` da ko'rsatish, `len()` da uzunligini olish, `+` operator bilan qo'shish kabi ishlarni qilishni xohlaysiz. Special Methods - bu Python'ga sizning class'ingizni qanday ishlatishni o'rgatadi.

class Talaba:
    def __init__(self, ism, yosh, kurs):
        self.ism = ism
        self.yosh = yosh
        self.kurs = kurs
        self.ball = 0
    
    def __str__(self):  # print() da ko'rsatish uchun
        return f"Talaba: {self.ism}, {self.yosh} yosh, {self.kurs}-kurs"
    
    def __len__(self):  # len() da uzunlik uchun
        return len(self.ism)
    
    def __eq__(self, boshqa):  # == operator uchun
        return self.ism == boshqa.ism and self.yosh == boshqa.yosh

โœ… Special Methods'ning afzalliklari

๐ŸŽฏ Tabiiy kod

Python'ning o'z operator'larini ishlatish

๐Ÿ“– Tushunarli kod

Qisqa va aniq sintaksis

๐Ÿ’ช Kuchli funksionallik

Murakkab operatsiyalar

๐Ÿ Python'ning ruhi

"Explicit is better than implicit"

๐Ÿ—๏ธ __init__, __str__, __repr__

__init__

def __init__(self, nom, muallif, yil, sahifalar):
    self.nom = nom
    self.muallif = muallif
    self.yil = yil
    self.sahifalar = sahifalar
    self.o_qilgan = False
    print(f"Kitob yaratildi: {self.nom}")

__str__

def __str__(self):  # print() da ko'rsatish uchun
    return f"'{self.nom}' - {self.muallif} ({self.yil})"
def __repr__(self):  # debug uchun
    return f"Kitob('{self.nom}', '{self.muallif}', {self.yil}, {self.sahifalar})"

# Test qilish
kitob1 = Kitob("Python", "Ali", 2023, 300)
kitob2 = Kitob("Java", "Zilola", 2022, 250)

print(kitob1)  # __str__ ishlaydi
print(repr(kitob1))  # __repr__ ishlaydi

๐Ÿ“ __len__, __bool__, __eq__

class Ro_yxat:
    def __init__(self, nom):
        self.nom = nom
        self.elementlar = []
    
    def __len__(self):  # len() uchun
        return len(self.elementlar)
    
    def __bool__(self):  # if, while uchun
        return len(self.elementlar) > 0
    
    def __eq__(self, boshqa):  # == operator uchun
        return self.nom == boshqa.nom and self.elementlar == boshqa.elementlar
    
    def element_qo_shish(self, element):
        self.elementlar.append(element)
        print(f"'{element}' qo'shildi!")
    
    def __str__(self):
        return f"{self.nom}: {self.elementlar}"

๐Ÿงช __len__, __bool__, __eq__ test

# Test qilish
ro_yxat1 = Ro_yxat("Bozor ro'yxati")
ro_yxat2 = Ro_yxat("Bozor ro'yxati")

print(f"Ro'yxat uzunligi: {len(ro_yxat1)}")  # __len__ ishlaydi
print(f"Ro'yxat bo'shmi: {not ro_yxat1}")  # __bool__ ishlaydi

ro_yxat1.element_qo_shish("Non")
ro_yxat1.element_qo_shish("Sut")
ro_yxat1.element_qo_shish("Go'sht")

print(f"Ro'yxat uzunligi: {len(ro_yxat1)}")  # __len__ ishlaydi
print(f"Ro'yxat bo'shmi: {not ro_yxat1}")  # __bool__ ishlaydi

ro_yxat2.element_qo_shish("Non")
ro_yxat2.element_qo_shish("Sut")
ro_yxat2.element_qo_shish("Go'sht")

print(f"Ro'yxatlar tengmi: {ro_yxat1 == ro_yxat2}")  # __eq__ ishlaydi

# if shartida ishlatish
if ro_yxat1:
    print("Ro'yxat bo'sh emas!")
else:
    print("Ro'yxat bo'sh!")

โž• Arifmetik operatorlar

๐Ÿ’ก Arifmetik operatorlar:

  • __add__ - + operator
  • __sub__ - - operator
  • __mul__ - * operator
  • __truediv__ - / operator
  • __floordiv__ - // operator
  • __mod__ - % operator
  • __pow__ - ** operator
class Vaqt:
    def __init__(self, soat, daqiqa):
        self.soat = soat
        self.daqiqa = daqiqa
        self.__normalizatsiya()
    
    def __normalizatsiya(self):
        if self.daqiqa >= 60:
            self.soat += self.daqiqa // 60
            self.daqiqa = self.daqiqa % 60
        if self.soat >= 24:
            self.soat = self.soat % 24
    
    def __add__(self, boshqa):  # + operator
        yangi_soat = self.soat + boshqa.soat
        yangi_daqiqa = self.daqiqa + boshqa.daqiqa
        return Vaqt(yangi_soat, yangi_daqiqa)

โž– Arifmetik operatorlar davomi

    def __sub__(self, boshqa):  # - operator
        yangi_soat = self.soat - boshqa.soat
        yangi_daqiqa = self.daqiqa - boshqa.daqiqa
        if yangi_daqiqa < 0:
            yangi_soat -= 1
            yangi_daqiqa += 60
        if yangi_soat < 0:
            yangi_soat += 24
        return Vaqt(yangi_soat, yangi_daqiqa)
    
    def __mul__(self, son):  # * operator
        yangi_soat = self.soat * son
        yangi_daqiqa = self.daqiqa * son
        return Vaqt(yangi_soat, yangi_daqiqa)
    
    def __str__(self):
        return f"{self.soat:02d}:{self.daqiqa:02d}"
    
    def __eq__(self, boshqa):
        return self.soat == boshqa.soat and self.daqiqa == boshqa.daqiqa

โฐ Vaqt test qilish

# Test qilish
vaqt1 = Vaqt(10, 30)  # 10:30
vaqt2 = Vaqt(2, 45)   # 02:45

print(f"vaqt1 = {vaqt1}")
print(f"vaqt2 = {vaqt2}")

qoshilma = vaqt1 + vaqt2  # __add__ ishlaydi
print(f"vaqt1 + vaqt2 = {qoshilma}")

ayirma = vaqt1 - vaqt2  # __sub__ ishlaydi
print(f"vaqt1 - vaqt2 = {ayirma}")

ko_paytma = vaqt1 * 2  # __mul__ ishlaydi
print(f"vaqt1 * 2 = {ko_paytma}")

print(f"vaqt1 == vaqt2: {vaqt1 == vaqt2}")  # __eq__ ishlaydi

๐Ÿ“ Amaliy loyiha: Vektor class

class Vektor:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):  # print() uchun
        return f"Vektor({self.x}, {self.y})"
    
    def __repr__(self):  # debug uchun
        return f"Vektor({self.x}, {self.y})"
    
    def __len__(self):  # len() uchun
        return 2  # Vektor har doim 2 o'lchamli
    
    def __bool__(self):  # if, while uchun
        return self.x != 0 or self.y != 0
    
    def __eq__(self, boshqa):  # == operator
        return self.x == boshqa.x and self.y == boshqa.y

๐Ÿ”ข Vektor arifmetik operatorlar

    def __add__(self, boshqa):  # + operator
        return Vektor(self.x + boshqa.x, self.y + boshqa.y)
    
    def __sub__(self, boshqa):  # - operator
        return Vektor(self.x - boshqa.x, self.y - boshqa.y)
    
    def __mul__(self, son):  # * operator
        return Vektor(self.x * son, self.y * son)
    
    def __truediv__(self, son):  # / operator
        if son != 0:
            return Vektor(self.x / son, self.y / son)
        else:
            raise ValueError("Nolga bo'lish mumkin emas!")
    
    def __floordiv__(self, son):  # // operator
        if son != 0:
            return Vektor(self.x // son, self.y // son)
        else:
            raise ValueError("Nolga bo'lish mumkin emas!")

๐Ÿ“Š Vektor qo'shimcha metodlar

    def __mod__(self, son):  # % operator
        if son != 0:
            return Vektor(self.x % son, self.y % son)
        else:
            raise ValueError("Nolga bo'lish mumkin emas!")
    
    def __pow__(self, son):  # ** operator
        return Vektor(self.x ** son, self.y ** son)
    
    def uzunlik(self):
        return (self.x**2 + self.y**2)**0.5
    
    def burchak(self):
        import math
        return math.atan2(self.y, self.x) * 180 / math.pi
    
    def ma_lumot_ko_rsatish(self):
        print(f"=== {self} ===")
        print(f"X: {self.x}")
        print(f"Y: {self.y}")
        print(f"Uzunlik: {self.uzunlik():.2f}")
        print(f"Burchak: {self.burchak():.2f}ยฐ")

๐Ÿงช Vektor test qilish

# Test qilish
v1 = Vektor(3, 4)
v2 = Vektor(1, 2)

print("=== Vektor ma'lumotlari ===")
v1.ma_lumot_ko_rsatish()
v2.ma_lumot_ko_rsatish()

print("\n=== Arifmetik operatsiyalar ===")
print(f"v1 = {v1}")
print(f"v2 = {v2}")
print(f"v1 + v2 = {v1 + v2}")
print(f"v1 - v2 = {v1 - v2}")
print(f"v1 * 2 = {v1 * 2}")
print(f"v1 / 2 = {v1 / 2}")
print(f"v1 // 2 = {v1 // 2}")
print(f"v1 % 2 = {v1 % 2}")
print(f"v1 ** 2 = {v1 ** 2}")

print("\n=== Solishtirish ===")
print(f"v1 == v2: {v1 == v2}")
print(f"v1 != v2: {v1 != v2}")

print("\n=== Boshqa operatsiyalar ===")
print(f"len(v1): {len(v1)}")
print(f"bool(v1): {bool(v1)}")
print(f"str(v1): {str(v1)}")
print(f"repr(v1): {repr(v1)}")

๐ŸŽฏ Mashq

๐Ÿ”ข Vazifa: Kompleks son class
  • Kompleks son class yarating
  • Xususiyatlar: real, imag
  • Special Methods: __init__, __str__, __repr__
  • Arifmetik operatorlar: +, -, *, /
  • Solishtirish operatorlari: ==, !=

Vaqt: 10 daqiqa โฐ

๐ŸŽ‰ Xulosa

Bugun nimalarni o'rgandik?

๐Ÿ—๏ธ Special Methods

__ bilan boshlanadi va tugaydi

๐Ÿ—๏ธ __init__

Constructor, object yaratilganda ishlaydi

๐Ÿ“– __str__

print() da ko'rsatish uchun

๐Ÿ” __repr__

debug va development uchun

โž• Arifmetik operatorlar

+, -, *, /, //, %, **

โš–๏ธ Solishtirish operatorlari

==, !=, <, >, <=, >=

Keyingi dars: Properties va Decorators mavzusini o'rganamiz

Savollaringiz bo'lsa, yozib qoldiring! ๐Ÿ˜Š