Assalomu alaykum, yosh dasturchilar! ๐
Bugun biz Python'ning juda qiziqarli va kuchli xususiyati - Special Methods'ni o'rganamiz
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
Python'ning o'z operator'larini ishlatish
Qisqa va aniq sintaksis
Murakkab operatsiyalar
"Explicit is better than implicit"
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}")
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
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}"
# 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:
__add__ - + operator__sub__ - - operator__mul__ - * operator__truediv__ - / operator__floordiv__ - // operator__mod__ - % operator__pow__ - ** operatorclass 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)
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
# 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
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
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!")
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}ยฐ")
# 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)}")
Vaqt: 10 daqiqa โฐ
__ bilan boshlanadi va tugaydi
Constructor, object yaratilganda ishlaydi
print() da ko'rsatish uchun
debug va development uchun
+, -, *, /, //, %, **
==, !=, <, >, <=, >=
Keyingi dars: Properties va Decorators mavzusini o'rganamiz
Savollaringiz bo'lsa, yozib qoldiring! ๐