8.9-dars: Polimorfizm
8-QISM — OBYEKTGA YO'NALTIRILGAN DASTURLASH · 9-dars
1. Kirish va motivatsiya
Bu funksiya hech qanday tur haqida bilmaydi:
def jami_yuza(shakllar):
return sum(s.yuza() for s in shakllar)Lekin ishlaydi:
jami_yuza([Doira(5), Kvadrat(3), Uchburchak(3, 4, 5)])
jami_yuza([Ellips(2, 3), Kop_burchak([...])])
jami_yuza([MeningShaklim()]) # ⭐ hali yozilmagan sinfBir shart bilan: har biri yuza() metodiga ega bo'lsin.
Va bu — Pythonning eng muhim xususiyati:
class Kvadrat: # ⭐ HECH NARSADAN meros olmagan
def __init__(self, a): self.a = a
def yuza(self): return self.a ** 2
jami_yuza([Kvadrat(3)]) # ✅ ishlaydiJava yoki C# da Kvadrat Shakl interfeysini amalga oshirishi shart. Pythonda — yo'q.
Bu darsda:
- Duck typing — Pythonning polimorfizm asosi
- To'rt xil polimorfizm
Protocol— statik duck typing (PEP 544)- ABC va
register()— virtual asos sinflar NotImplementedva ikkilamchi amallarfunctools.singledispatch— tur bo'yicha yuborish
2. Nazariya — chuqur tushuntirish
2.1. Polimorfizm nima
Polimorfizm (yunoncha: "ko'p shakl") — bir xil interfeys, turli amalga oshirish.
len("abc") # 3 — str.__len__
len([1, 2]) # 2 — list.__len__
len({"a": 1}) # 1 — dict.__len__ len() — bitta funksiya, lekin har tur o'zicha hisoblaydi.
To'rt xil polimorfizm:
| Tur | Pythonda | Misol |
|---|---|---|
| Ad-hoc (ortiqcha yuklash) | To'g'ridan-to'g'ri yo'q | singledispatch |
| Parametrik (generiklar) | Duck typing, TypeVar |
list[T] |
| Subtip (meros) | Meros | Doira(Shakl) |
| Strukturaviy (duck typing) | Asosiy | .yuza() bo'lsa yetadi |
2.2. Duck typing
"Agar u o'rdak kabi yursa va o'rdak kabi qichqirsa — u o'rdak."
class Oquvchi:
def oqi(self): return "haqiqiy"
class SoxtaOquvchi: # ⭐ meros yo'q
def oqi(self): return "soxta"
def ishla(manba):
return manba.oqi() # ⭐ tur tekshirilmaydi
ishla(Oquvchi()) # 'haqiqiy'
ishla(SoxtaOquvchi()) # 'soxta'Muhim natijalar:
- Meros shart emas — faqat metod nomi
- Test qilish oson — soxta obyekt yozish yetarli
- Kengaytiriladigan — sizning kodingizga tegmasdan yangi tur qo'shiladi
- Xatolar ish vaqtida — statik tekshiruv yo'q (
mypyyordam beradi)
EAFP vs LBYL:
# LBYL — "Look Before You Leap" (sakrashdan oldin qara)
if hasattr(x, "oqi"): # ⚠️ ko'p tekshiruv
x.oqi()
# ⭐ EAFP — "Easier to Ask Forgiveness than Permission"
try:
x.oqi()
except AttributeError:
...Python EAFP ni afzal ko'radi.
2.3. Dunder metodlar orqali polimorfizm
Pythonning o'rnatilgan amallari — polimorf:
len(x) # x.__len__()
x + y # x.__add__(y)
x[0] # x.__getitem__(0)
for i in x: # x.__iter__()
str(x) # x.__str__()
x == y # x.__eq__(y)
with x: # x.__enter__() / x.__exit__()
x(1) # x.__call__(1)Sinfingizga bu metodlarni qo'shsangiz — u o'rnatilgan turlar bilan bir xil ishlaydi:
class Vektor:
def __init__(self, *k): self.k = k
def __len__(self): return len(self.k)
def __getitem__(self, i): return self.k[i]
def __add__(self, b): return Vektor(*(x+y for x, y in zip(self.k, b.k)))
v = Vektor(1, 2, 3)
len(v) # 3
v[0] # 1
list(v) # [1, 2, 3] ← __getitem__ dan iteratsiya
v + Vektor(10, 20, 30) # Vektor(11, 22, 33)Dunder metodlar — 8.11-8.14-darslarda batafsil.
2.4. Protocol — statik duck typing
PEP 544 (Python 3.8):
from typing import Protocol
class Yuzali(Protocol):
def yuza(self) -> float: ...
def jami(shakllar: list[Yuzali]) -> float:
return sum(s.yuza() for s in shakllar)
class Kvadrat: # ⭐ meros YO'Q
def __init__(self, a): self.a = a
def yuza(self) -> float: return self.a ** 2
jami([Kvadrat(3)]) # ✅ mypy ham rozi Protocol — duck typing ni statik tekshiruvga olib keladi.
| ABC | Protocol | |
|---|---|---|
| Meros | Majburiy | Kerak emas |
| Tekshirish | Ish vaqtida | Statik (mypy) |
isinstance |
Har doim | @runtime_checkable bilan |
| Mavjud sinflar | register() kerak |
Avtomatik |
| Sukut amalga oshirish | Mumkin | Mumkin (3.8+) |
@runtime_checkable:
from typing import Protocol, runtime_checkable
@runtime_checkable
class Yuzali(Protocol):
def yuza(self) -> float: ...
isinstance(Kvadrat(3), Yuzali) # True ✅Faqat metod nomlari tekshiriladi, imzo emas:
class Yolgonchi:
def yuza(self, a, b, c): ... # boshqa imzo
isinstance(Yolgonchi(), Yuzali) # True ⚠️2.5. ABC — abstrakt asos sinflar
from abc import ABC, abstractmethod
class Shakl(ABC):
@abstractmethod
def yuza(self) -> float: ...
def tavsif(self) -> str: # ⭐ sukut amalga oshirish
return f"{type(self).__name__}: {self.yuza():.2f}"
Shakl() # ❌ TypeError — abstrakt register() — virtual asos sinf:
class Boshqa: # meros yo'q
def yuza(self): return 42
Shakl.register(Boshqa) # ⭐ "virtual" avlod
isinstance(Boshqa(), Shakl) # True ✅
issubclass(Boshqa, Shakl) # True ✅
Boshqa.__mro__ # (Boshqa, object) — Shakl YO'Q register() tekshirmaydi — metod bo'lmasa ham True qaytaradi.
__subclasshook__ — avtomatik tekshiruv:
class Yuzali(ABC):
@classmethod
def __subclasshook__(cls, C):
if cls is Yuzali:
return any("yuza" in B.__dict__ for B in C.__mro__)
return NotImplemented
isinstance(Kvadrat(3), Yuzali) # True ✅ avtomatikBu — collections.abc ishlash usuli. ABC to'liq — 8.18-darsda.
2.6. NotImplemented va ikkilamchi amallar
class Pul:
def __init__(self, miqdor, valyuta="UZS"):
self.miqdor, self.valyuta = miqdor, valyuta
def __add__(self, boshqa):
if not isinstance(boshqa, Pul):
return NotImplemented # ⭐ "men bilmayman"
if self.valyuta != boshqa.valyuta:
raise ValueError("Valyutalar mos emas")
return Pul(self.miqdor + boshqa.miqdor, self.valyuta) NotImplemented qaytarilsa, Python boshqa.__radd__(self) ni sinaydi:
a + b:
1. a.__add__(b) → NotImplemented bo'lsa
2. b.__radd__(a) → NotImplemented bo'lsa
3. TypeError NotImplemented ≠ NotImplementedError:
| Nima | Qachon | |
|---|---|---|
NotImplemented |
Qiymat (singleton) | Ikkilamchi amallar |
NotImplementedError |
Istisno | Abstrakt metod |
def __eq__(self, b):
return NotImplemented # ✅ qaytariladi
@abstractmethod
def f(self):
raise NotImplementedError # ✅ tashlandi2.7. singledispatch — tur bo'yicha yuborish
Ba'zan metod qo'shib bo'lmaydi (o'rnatilgan turlar):
from functools import singledispatch
@singledispatch
def formatla(x) -> str:
return f"noma'lum: {x!r}"
@formatla.register
def _(x: int) -> str:
return f"son: {x:,}"
@formatla.register
def _(x: str) -> str:
return f"satr: {x!r}"
@formatla.register(list)
def _(x) -> str:
return f"ro'yxat ({len(x)} element)"
formatla(1234) # 'son: 1,234'
formatla("ab") # "satr: 'ab'"
formatla([1, 2]) # "ro'yxat (2 element)"
formatla(3.14) # "noma'lum: 3.14"Bu — ad-hoc polimorfizm (ortiqcha yuklash).
Metodlar uchun singledispatchmethod:
from functools import singledispatchmethod
class Ishlovchi:
@singledispatchmethod
def ishla(self, x):
raise TypeError(f"Qo'llab-quvvatlanmaydi: {type(x).__name__}")
@ishla.register
def _(self, x: int): return x * 2
@ishla.register
def _(self, x: str): return x.upper()3. Tez ma'lumotnoma
Duck typing
def f(x):
return x.metod() # tur tekshirilmaydi
# Meros SHART EMAS — metod nomi yetadi
# EAFP: try/except, hasattr emasProtocol (statik duck typing)
from typing import Protocol, runtime_checkable
@runtime_checkable
class Yuzali(Protocol):
def yuza(self) -> float: ...
def f(x: Yuzali): ... ✅ mypy tekshiradi
isinstance(x, Yuzali) ⚠️ faqat nom, imzo emasABC
from abc import ABC, abstractmethod
class Shakl(ABC):
@abstractmethod
def yuza(self): ...
def tavsif(self): ... sukut amalga oshirish
Shakl.register(Boshqa) virtual avlod (tekshirmaydi!)
__subclasshook__ avtomatik tekshiruvNotImplemented
a + b:
a.__add__(b) → NotImplemented
b.__radd__(a) → NotImplemented
TypeError
NotImplemented qiymat, ikkilamchi amallar
NotImplementedError istisno, abstrakt metodsingledispatch
@singledispatch
def f(x): ... sukut
@f.register
def _(x: int): ... int uchun
@singledispatchmethod metodlar uchun4. Batafsil misollar
Misol 1 — Duck typing
"""Pythonda polimorfizm merosni talab qilmaydi."""
import math
from dataclasses import dataclass
print("=== 1. Merossiz polimorfizm ===\n")
@dataclass
class Doira:
r: float
def yuza(self) -> float: return math.pi * self.r ** 2
def perimetr(self) -> float: return 2 * math.pi * self.r
@dataclass
class Kvadrat: # ⭐ Doira bilan bog'liq emas
a: float
def yuza(self) -> float: return self.a ** 2
def perimetr(self) -> float: return 4 * self.a
@dataclass
class Uchburchak:
a: float
b: float
c: float
def yuza(self) -> float:
p = (self.a + self.b + self.c) / 2
return math.sqrt(p * (p-self.a) * (p-self.b) * (p-self.c))
def perimetr(self) -> float: return self.a + self.b + self.c
def hisobot(shakllar) -> None:
"""⭐ Turlarni BILMAYDI."""
print(f" {'Shakl':<30} {'Yuza':>10} {'Perimetr':>10}")
print(" " + "─" * 52)
for s in shakllar:
print(f" {str(s):<30} {s.yuza():>10.2f} {s.perimetr():>10.2f}")
print(f" {'JAMI':<30} {sum(s.yuza() for s in shakllar):>10.2f} "
f"{sum(s.perimetr() for s in shakllar):>10.2f}")
SHAKLLAR = [Doira(5), Kvadrat(4), Uchburchak(3, 4, 5)]
hisobot(SHAKLLAR)
print(f"\n Meros zanjirlari:")
for S in (Doira, Kvadrat, Uchburchak):
print(f" {S.__name__:<14} {[k.__name__ for k in S.__mro__]}")
print(f"\n ⭐ Umumiy ota-sinf: faqat object")
print(f" Lekin hisobot() hammasi bilan ishlaydi.")
print("\n=== 2. Yangi tur qo'shish ===\n")
class Ellips: # ⭐ hozir yozildi
def __init__(self, a, b): self.a, self.b = a, b
def yuza(self): return math.pi * self.a * self.b
def perimetr(self):
return math.pi * (3*(self.a+self.b) -
math.sqrt((3*self.a+self.b)*(self.a+3*self.b)))
def __repr__(self): return f"Ellips({self.a}, {self.b})"
class Halqa:
def __init__(self, tashqi, ichki):
self.tashqi, self.ichki = tashqi, ichki
def yuza(self): return math.pi * (self.tashqi**2 - self.ichki**2)
def perimetr(self): return 2 * math.pi * (self.tashqi + self.ichki)
def __repr__(self): return f"Halqa({self.tashqi}, {self.ichki})"
hisobot(SHAKLLAR + [Ellips(3, 5), Halqa(5, 3)])
print(f"\n ⭐ hisobot() KODI O'ZGARMADI.")
print(f" Bu — 'Ochiq/yopiq tamoyili' (Open/Closed Principle).")
print("\n=== 3. Test uchun soxta obyekt ===\n")
class SoxtaShakl:
"""⭐ Testda ishlatiladi — meros kerak emas."""
def __init__(self, yuza=1.0, perimetr=1.0):
self._yuza, self._perimetr = yuza, perimetr
self.chaqiruvlar = {"yuza": 0, "perimetr": 0}
def yuza(self):
self.chaqiruvlar["yuza"] += 1
return self._yuza
def perimetr(self):
self.chaqiruvlar["perimetr"] += 1
return self._perimetr
def __repr__(self): return f"SoxtaShakl({self._yuza})"
soxta = [SoxtaShakl(10), SoxtaShakl(20), SoxtaShakl(30)]
hisobot(soxta)
print(f"\n Chaqiruvlar hisobi:")
for s in soxta:
print(f" {s} → {s.chaqiruvlar}")
print(f"""
⭐ Java/C# da bu uchun:
• Interfeys yaratish
• Mock kutubxona
• Yoki sinfni `virtual` qilish kerak
Pythonda — oddiy sinf yetadi.
""")
print("=== 4. EAFP vs LBYL ===\n")
class Toliq:
def yuza(self): return 10
def perimetr(self): return 20
class Chala:
def yuza(self): return 5
# perimetr yo'q
class Umuman:
pass
OBYEKTLAR = [Toliq(), Chala(), Umuman(), "satr", 42, None]
def lbyl(obyektlar):
"""⚠️ Har amaldan oldin tekshirish."""
natija = []
for o in obyektlar:
if hasattr(o, "yuza") and callable(getattr(o, "yuza")):
if hasattr(o, "perimetr") and callable(getattr(o, "perimetr")):
natija.append((type(o).__name__, o.yuza(), o.perimetr()))
else:
natija.append((type(o).__name__, o.yuza(), None))
else:
natija.append((type(o).__name__, None, None))
return natija
def eafp(obyektlar):
"""⭐ Urinib ko'rish, xatoni ushlash."""
natija = []
for o in obyektlar:
try:
yuza = o.yuza()
except (AttributeError, TypeError):
yuza = None
try:
perimetr = o.perimetr()
except (AttributeError, TypeError):
perimetr = None
natija.append((type(o).__name__, yuza, perimetr))
return natija
print(f" {'Obyekt':<12} {'LBYL':<22} {'EAFP'}")
print(" " + "─" * 56)
for (n1, y1, p1), (n2, y2, p2) in zip(lbyl(OBYEKTLAR), eafp(OBYEKTLAR)):
print(f" {n1:<12} {f'({y1}, {p1})':<22} {f'({y2}, {p2})'}")
print(f"""
⭐ EAFP AFZALLIKLARI:
• Qisqaroq
• Poyga holati (race condition) yo'q
(LBYL da tekshiruv va ishlatish orasida o'zgarishi mumkin)
• Tez (istisno tashlanmasa)
⚠️ EAFP KAMCHILIKLARI:
• Istisno qimmat (tashlansa)
• Kutilmagan xatoni yashirishi mumkin
→ aniq istisno turini yozing
⭐ QOIDA: odatda EAFP, lekin istisno TEZ-TEZ bo'lsa — LBYL
""")
print("=== ⚠️ 5. Duck typing xavflari ===\n")
class Otish:
def otish(self): return "o'q otildi"
class Kamera:
def otish(self): return "rasm olindi" # ⚠️ bir xil nom!
def bajar(obj):
return obj.otish()
print(f" bajar(Otish()) = {bajar(Otish())!r}")
print(f" bajar(Kamera()) = {bajar(Kamera())!r} ⚠️ butunlay boshqa ma'no!")
print(f"""
⚠️ MUAMMO: duck typing NOMGA qaraydi, MA'NOGA emas.
✅ YECHIMLAR:
1. Aniq nomlar: o_otish() va rasm_olish()
2. Protocol + mypy
3. ABC + isinstance (chegarada)
4. Nomlar konventsiyasini hujjatlash
""")
class Nusxalanadigan:
def nusxa(self): return "sayoz nusxa"
class Yozuvchi:
def nusxa(self, manba): return f"{manba} dan nusxalandi"
for obj in [Nusxalanadigan(), Yozuvchi()]:
try:
n = f"✅ {obj.nusxa()!r}"
except TypeError as e:
n = f"❌ TypeError: {e}"
print(f" {type(obj).__name__:<18} obj.nusxa() → {n}")
print(f"\n ⚠️ IMZO ham mos kelishi kerak — duck typing buni")
print(f" ish vaqtigacha tekshirmaydi.")Natijaning muhim qismi:
=== 1. Merossiz polimorfizm ===
Shakl Yuza Perimetr
────────────────────────────────────────────────────
Doira(r=5) 78.54 31.42
Kvadrat(a=4) 16.00 16.00
Uchburchak(a=3, b=4, c=5) 6.00 12.00
JAMI 100.54 59.42
Meros zanjirlari:
Doira ['Doira', 'object']
Kvadrat ['Kvadrat', 'object']
=== 4. EAFP vs LBYL ===
Obyekt LBYL EAFP
────────────────────────────────────────────────────────
Toliq (10, 20) (10, 20)
Chala (5, None) (5, None)
Umuman (None, None) (None, None)
str (None, None) (None, None)
=== ⚠️ 5. Duck typing xavflari ===
bajar(Otish()) = "o'q otildi"
bajar(Kamera()) = 'rasm olindi' ⚠️ butunlay boshqa ma'no!Nima ko'rsatdi: 2.1, 2.2-bo'limlar.
Misol 2 — Protocol va ABC
"""Statik va ish vaqtidagi interfeys tekshiruvi."""
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable
import math
print("=== 1. Protocol — statik duck typing ===\n")
@runtime_checkable
class Yuzali(Protocol):
"""Yuza hisoblay oladigan har narsa."""
def yuza(self) -> float: ...
@runtime_checkable
class Chizilar(Protocol):
def chiz(self) -> str: ...
@runtime_checkable
class ToliqShakl(Yuzali, Chizilar, Protocol):
"""⭐ Protokollarni birlashtirish."""
def perimetr(self) -> float: ...
class Kvadrat: # ⭐ meros YO'Q
def __init__(self, a): self.a = a
def yuza(self) -> float: return self.a ** 2
def perimetr(self) -> float: return 4 * self.a
def chiz(self) -> str: return "□"
class Doira:
def __init__(self, r): self.r = r
def yuza(self) -> float: return math.pi * self.r ** 2
class Nuqta:
def __init__(self, x, y): self.x, self.y = x, y
OBYEKTLAR = [Kvadrat(3), Doira(2), Nuqta(0, 0), "satr", 42]
print(f" {'Obyekt':<12} {'Yuzali':<10} {'Chizilar':<10} {'ToliqShakl'}")
print(" " + "─" * 46)
for o in OBYEKTLAR:
print(f" {type(o).__name__:<12} "
f"{str(isinstance(o, Yuzali)):<10} "
f"{str(isinstance(o, Chizilar)):<10} "
f"{isinstance(o, ToliqShakl)}")
print(f"""
⭐ isinstance() ishladi, lekin HECH BIRI meros olmagan.
Protocol faqat METOD NOMLARINI tekshiradi.
""")
print("=== ⚠️ 2. Protocol imzoni tekshirmaydi ===\n")
class Yolgonchi:
def yuza(self, a, b, c): # ⚠️ butunlay boshqa imzo
return a + b + c
class Yolgonchi2:
yuza = "bu satr, metod emas" # ⚠️ callable emas
print(f" isinstance(Yolgonchi(), Yuzali) = "
f"{isinstance(Yolgonchi(), Yuzali)} ⚠️")
print(f" isinstance(Yolgonchi2(), Yuzali) = "
f"{isinstance(Yolgonchi2(), Yuzali)} ⚠️")
try:
Yolgonchi().yuza()
except TypeError as e:
print(f"\n Yolgonchi().yuza() → ❌ TypeError: {e}")
print(f"""
⚠️ isinstance + Protocol — FAQAT ish vaqtida nom tekshiruvi.
✅ HAQIQIY TEKSHIRUV — mypy:
def f(x: Yuzali) -> float:
return x.yuza()
f(Yolgonchi())
→ mypy: Argument 1 has incompatible type "Yolgonchi";
expected "Yuzali"
""")
print("=== 3. ABC — abstrakt asos sinf ===\n")
class Shakl(ABC):
"""Abstrakt asos sinf."""
@abstractmethod
def yuza(self) -> float:
"""Har avlod MAJBURIY amalga oshiradi."""
@abstractmethod
def perimetr(self) -> float: ...
def tavsif(self) -> str:
"""⭐ Sukut amalga oshirish — meros olinadi."""
return (f"{type(self).__name__}: yuza={self.yuza():.2f}, "
f"perimetr={self.perimetr():.2f}")
def kattaroqmi(self, boshqa: "Shakl") -> bool:
return self.yuza() > boshqa.yuza()
class KvadratABC(Shakl):
def __init__(self, a): self.a = a
def yuza(self): return self.a ** 2
def perimetr(self): return 4 * self.a
class ChalaShakl(Shakl):
def yuza(self): return 1
# ⚠️ perimetr yo'q
print(f" Shakl() (abstrakt):")
try:
Shakl()
except TypeError as e:
print(f" ❌ TypeError: {e}")
print(f"\n ChalaShakl() (perimetr yo'q):")
try:
ChalaShakl()
except TypeError as e:
print(f" ❌ TypeError: {e}")
print(f"\n KvadratABC(3):")
k = KvadratABC(3)
print(f" ✅ {k.tavsif()}")
print(f" kattaroqmi: {k.kattaroqmi(KvadratABC(2))}")
print(f"\n Abstrakt metodlar: {Shakl.__abstractmethods__}")
print("\n=== 4. ⭐ register() — virtual avlod ===\n")
class Boshqacha:
"""Shakl dan meros OLMAGAN."""
def yuza(self): return 42
def perimetr(self): return 24
print(f" Ro'yxatga olishdan OLDIN:")
print(f" isinstance(Boshqacha(), Shakl) = {isinstance(Boshqacha(), Shakl)}")
Shakl.register(Boshqacha) # ⭐
print(f"\n Shakl.register(Boshqacha) dan KEYIN:")
print(f" isinstance(Boshqacha(), Shakl) = {isinstance(Boshqacha(), Shakl)}")
print(f" issubclass(Boshqacha, Shakl) = {issubclass(Boshqacha, Shakl)}")
print(f" Boshqacha.__mro__ = "
f"{[c.__name__ for c in Boshqacha.__mro__]} ⚠️ Shakl YO'Q")
b = Boshqacha()
try:
print(f" b.tavsif() → {b.tavsif()}")
except AttributeError as e:
print(f" b.tavsif() → ❌ AttributeError: {e}")
print(f" ⚠️ Sukut metodlar meros OLINMAYDI")
class Yolgon:
"""⚠️ Hech qanday metod yo'q."""
pass
Shakl.register(Yolgon)
print(f"\n ⚠️ register() TEKSHIRMAYDI:")
print(f" Shakl.register(Yolgon)")
print(f" isinstance(Yolgon(), Shakl) = {isinstance(Yolgon(), Shakl)} ⚠️")
try:
Yolgon().yuza()
except AttributeError as e:
print(f" Yolgon().yuza() → ❌ AttributeError")
print("\n=== 5. __subclasshook__ — avtomatik tekshiruv ===\n")
class AvtoYuzali(ABC):
"""⭐ yuza() metodi bo'lgan HAR sinfni tanadi."""
@classmethod
def __subclasshook__(cls, C):
if cls is AvtoYuzali:
return any("yuza" in B.__dict__ for B in C.__mro__)
return NotImplemented
@abstractmethod
def yuza(self) -> float: ...
TEKSHIRUV = [Kvadrat(3), Doira(2), Boshqacha(), Nuqta(0, 0), "satr"]
print(f" {'Obyekt':<14} {'isinstance(x, AvtoYuzali)'}")
print(" " + "─" * 44)
for o in TEKSHIRUV:
print(f" {type(o).__name__:<14} {isinstance(o, AvtoYuzali)}")
print(f"""
⭐ Bu — collections.abc ishlash usuli:
from collections.abc import Sized, Iterable, Container
isinstance([1,2], Sized) True (__len__ bor)
isinstance("ab", Iterable) True (__iter__ bor)
""")
from collections.abc import Sized, Iterable, Container, Hashable, Callable
print(f" collections.abc misollari:\n")
print(f" {'Obyekt':<14} {'Sized':<8} {'Iterable':<10} "
f"{'Container':<11} {'Hashable'}")
print(" " + "─" * 56)
for o in [[1, 2], "ab", {"a": 1}, 42, (x for x in [1])]:
nom = type(o).__name__
print(f" {nom:<14} {str(isinstance(o, Sized)):<8} "
f"{str(isinstance(o, Iterable)):<10} "
f"{str(isinstance(o, Container)):<11} "
f"{isinstance(o, Hashable)}")
print("\n=== 6. Protocol vs ABC — tanlash ===\n")
print("""
┌──────────────────────┬─────────────────┬─────────────────┐
│ Mezon │ ABC │ Protocol │
├──────────────────────┼─────────────────┼─────────────────┤
│ Meros │ ✅ majburiy │ ❌ kerak emas │
│ Tekshirish vaqti │ Nusxa yaratishda│ Statik (mypy) │
│ isinstance │ ✅ har doim │ ⚠️ runtime_check│
│ Sukut metodlar │ ✅ meros │ ⚠️ faqat mypy │
│ Mavjud/tashqi sinf │ register() │ ✅ avtomatik │
│ Imzo tekshiruvi │ ❌ │ ✅ mypy bilan │
│ Ish vaqti narxi │ ⚠️ bor │ ✅ yo'q │
└──────────────────────┴─────────────────┴─────────────────┘
⭐ TANLASH:
Protocol:
• Tashqi/mavjud sinflar bilan ishlaysiz
• Kod almashtiriladigan bo'lsin
• mypy ishlatasiz
• Faqat interfeys kerak (kod yo'q)
ABC:
• O'z ierarxiyangizni quryapsiz
• Sukut amalga oshirish kerak
• Ish vaqtida majburlash kerak
• __init_subclass__ bilan tekshiruv
⭐ IKKALASI:
class Ombor(Protocol): ... # tashqi kod uchun
class AsosOmbor(ABC): ... # o'z avlodlaringiz uchun
""")Natijaning muhim qismi:
=== 1. Protocol — statik duck typing ===
Obyekt Yuzali Chizilar ToliqShakl
──────────────────────────────────────────────
Kvadrat True True True
Doira True False False
Nuqta False False False
=== ⚠️ 2. Protocol imzoni tekshirmaydi ===
isinstance(Yolgonchi(), Yuzali) = True ⚠️
Yolgonchi().yuza() → ❌ TypeError: Yolgonchi.yuza() missing 3 required positional arguments: 'a', 'b', and 'c'
=== 4. ⭐ register() — virtual avlod ===
Shakl.register(Boshqacha) dan KEYIN:
isinstance(Boshqacha(), Shakl) = True
Boshqacha.__mro__ = ['Boshqacha', 'object'] ⚠️ Shakl YO'Q
b.tavsif() → ❌ AttributeError
⚠️ Sukut metodlar meros OLINMAYDI
=== 5. __subclasshook__ — avtomatik tekshiruv ===
Obyekt isinstance(x, AvtoYuzali)
────────────────────────────────────────────
Kvadrat True
Nuqta FalseNima ko'rsatdi: 2.4, 2.5-bo'limlar.
Misol 3 — Dunder metodlar va NotImplemented
"""O'rnatilgan amallar orqali polimorfizm."""
from __future__ import annotations
from dataclasses import dataclass
from functools import total_ordering
print("=== 1. Dunder metodlar — o'rnatilgan polimorfizm ===\n")
class Vektor:
"""Barcha o'rnatilgan amallarni qo'llab-quvvatlaydi."""
def __init__(self, *komponentlar: float):
self._k = tuple(float(x) for x in komponentlar)
# ── Konteyner protokoli ──
def __len__(self): return len(self._k)
def __getitem__(self, i): return self._k[i]
def __iter__(self): return iter(self._k)
def __contains__(self, x): return x in self._k
def __reversed__(self): return reversed(self._k)
# ── Ko'rinish ──
def __repr__(self): return f"Vektor{self._k}"
def __str__(self): return f"<{', '.join(f'{x:g}' for x in self._k)}>"
def __format__(self, spec):
if spec == "u": # uzunlik
return f"{abs(self):.4f}"
return str(self)
# ── Arifmetika ──
def __add__(self, b):
if not isinstance(b, Vektor):
return NotImplemented # ⭐
if len(self) != len(b):
raise ValueError("O'lchamlar mos emas")
return Vektor(*(x + y for x, y in zip(self, b)))
def __sub__(self, b):
if not isinstance(b, Vektor):
return NotImplemented
return Vektor(*(x - y for x, y in zip(self, b)))
def __mul__(self, b):
if isinstance(b, (int, float)):
return Vektor(*(x * b for x in self)) # skalyar
if isinstance(b, Vektor):
return sum(x * y for x, y in zip(self, b)) # skalyar ko'paytma
return NotImplemented
def __rmul__(self, b):
"""⭐ 3 * v uchun."""
return self.__mul__(b)
def __neg__(self): return Vektor(*(-x for x in self))
def __abs__(self): return sum(x ** 2 for x in self) ** 0.5
# ── Taqqoslash ──
def __eq__(self, b):
if not isinstance(b, Vektor):
return NotImplemented
return self._k == b._k
def __lt__(self, b):
if not isinstance(b, Vektor):
return NotImplemented
return abs(self) < abs(b)
def __hash__(self): return hash(self._k)
# ── Boshqalar ──
def __bool__(self): return any(self._k)
def __call__(self, koeff): return self * koeff
v1 = Vektor(1, 2, 3)
v2 = Vektor(4, 5, 6)
AMALLAR = [
("len(v1)", lambda: len(v1)),
("v1[0]", lambda: v1[0]),
("v1[-1]", lambda: v1[-1]),
("list(v1)", lambda: list(v1)),
("2 in v1", lambda: 2 in v1),
("list(reversed(v1))", lambda: list(reversed(v1))),
("str(v1)", lambda: str(v1)),
("f'{v1:u}'", lambda: f"{v1:u}"),
("v1 + v2", lambda: v1 + v2),
("v1 - v2", lambda: v1 - v2),
("v1 * 3", lambda: v1 * 3),
("3 * v1", lambda: 3 * v1),
("v1 * v2", lambda: v1 * v2),
("-v1", lambda: -v1),
("abs(v1)", lambda: round(abs(v1), 4)),
("v1 == Vektor(1,2,3)", lambda: v1 == Vektor(1, 2, 3)),
("v1 < v2", lambda: v1 < v2),
("bool(Vektor(0,0))", lambda: bool(Vektor(0, 0))),
("v1(2)", lambda: v1(2)),
("sorted([v2, v1])", lambda: sorted([v2, v1])),
("{v1, Vektor(1,2,3)}", lambda: len({v1, Vektor(1, 2, 3)})),
("sum([v1, v2], Vektor(0,0,0))", lambda: sum([v1, v2],
Vektor(0, 0, 0))),
]
for kod, f in AMALLAR:
print(f" {kod:<32} → {f()!r}")
print("\n\n=== ⭐ 2. NotImplemented mexanizmi ===\n")
class Chap:
def __add__(self, b):
print(f" Chap.__add__({type(b).__name__}) chaqirildi")
return NotImplemented # ⭐ "men bilmayman"
class Ong:
def __radd__(self, b):
print(f" Ong.__radd__({type(b).__name__}) chaqirildi")
return "Ong hal qildi"
class Bilmaydi:
pass
print(f" Chap() + Ong():")
n = Chap() + Ong()
print(f" natija: {n!r}\n")
print(f" Chap() + Bilmaydi():")
try:
Chap() + Bilmaydi()
except TypeError as e:
print(f" ❌ TypeError: {e}")
print(f"""
⭐ MEXANIZM (a + b):
1. a.__add__(b) → NotImplemented bo'lsa
2. b.__radd__(a) → NotImplemented bo'lsa
3. TypeError
⚠️ Agar type(b) — type(a) ning AVLODI bo'lsa,
b.__radd__ BIRINCHI chaqiriladi.
""")
class Ota:
def __add__(self, b):
return "Ota.__add__"
class Bola(Ota):
def __radd__(self, b):
return "Bola.__radd__" # ⭐ avlod ustuvor
print(f" Ota() + Bola() = {Ota() + Bola()!r} ⭐ avlod birinchi")
print("\n=== ⚠️ 3. NotImplemented vs NotImplementedError ===\n")
class Togri:
def __eq__(self, b):
if not isinstance(b, Togri):
return NotImplemented # ✅ QIYMAT
class Notogri:
def __eq__(self, b):
if not isinstance(b, Notogri):
raise NotImplementedError # ⚠️ ISTISNO
print(f" Togri() == 42:")
print(f" natija: {Togri() == 42} ✅ False (Python fallback qiladi)")
print(f"\n Notogri() == 42:")
try:
Notogri() == 42
except NotImplementedError:
print(f" ❌ NotImplementedError — dastur to'xtadi")
print(f"""
┌──────────────────────┬────────────┬──────────────────────┐
│ │ Tur │ Qachon │
├──────────────────────┼────────────┼──────────────────────┤
│ NotImplemented │ Singleton │ Ikkilamchi amallarda │
│ │ (qiymat) │ QAYTARILADI │
│ NotImplementedError │ Istisno │ Abstrakt metodda │
│ │ │ TASHLANADI │
└──────────────────────┴────────────┴──────────────────────┘
⚠️ if x is NotImplemented — DeprecationWarning (3.9+)
bool(NotImplemented) → xato bo'ladi kelajakda
""")
print("=== 4. total_ordering ===\n")
@total_ordering
@dataclass
class Versiya:
"""⭐ __eq__ va __lt__ dan qolgan hammasi avtomatik."""
katta: int
kichik: int
tuzatish: int = 0
def _kalit(self):
return (self.katta, self.kichik, self.tuzatish)
def __eq__(self, b):
if not isinstance(b, Versiya):
return NotImplemented
return self._kalit() == b._kalit()
def __lt__(self, b):
if not isinstance(b, Versiya):
return NotImplemented
return self._kalit() < b._kalit()
def __hash__(self):
return hash(self._kalit())
def __str__(self):
return f"{self.katta}.{self.kichik}.{self.tuzatish}"
VERSIYALAR = [Versiya(3, 12), Versiya(3, 9, 7), Versiya(2, 7, 18),
Versiya(3, 12, 1)]
print(f" Faqat __eq__ va __lt__ yozildi, lekin:")
v1, v2 = Versiya(3, 12), Versiya(3, 9, 7)
for kod, natija in [
("v1 < v2", v1 < v2), ("v1 > v2", v1 > v2),
("v1 <= v2", v1 <= v2), ("v1 >= v2", v1 >= v2),
("v1 == v2", v1 == v2), ("v1 != v2", v1 != v2),
]:
print(f" {kod:<12} {natija}")
print(f"\n Saralash: {[str(v) for v in sorted(VERSIYALAR)]}")
print(f" max: {max(VERSIYALAR)}, min: {min(VERSIYALAR)}")
print(f"\n ⚠️ total_ordering sekinroq (zanjirli chaqiruv).")
print(f" Tezlik muhim bo'lsa — hammasini qo'lda yozing.")
print("\n=== 5. singledispatch ===\n")
from functools import singledispatch, singledispatchmethod
from decimal import Decimal
from datetime import date, datetime
@singledispatch
def ozbekcha(x) -> str:
"""Sukut amalga oshirish."""
return f"noma'lum tur: {type(x).__name__}"
@ozbekcha.register
def _(x: int) -> str:
BIRLIK = ("nol", "bir", "ikki", "uch", "to'rt",
"besh", "olti", "yetti", "sakkiz", "to'qqiz")
if 0 <= x < 10:
return BIRLIK[x]
return f"{x:,}".replace(",", " ")
@ozbekcha.register
def _(x: float) -> str:
return f"{x:.2f}".replace(".", ",")
@ozbekcha.register
def _(x: str) -> str:
return f"«{x}»"
@ozbekcha.register
def _(x: bool) -> str: # ⭐ int dan OLDIN
return "ha" if x else "yo'q"
@ozbekcha.register(list)
@ozbekcha.register(tuple)
def _(x) -> str:
return ", ".join(ozbekcha(e) for e in x)
@ozbekcha.register
def _(x: dict) -> str:
return "{" + ", ".join(f"{ozbekcha(k)}: {ozbekcha(v)}"
for k, v in x.items()) + "}"
@ozbekcha.register
def _(x: date) -> str:
OYLAR = ("yanvar", "fevral", "mart", "aprel", "may", "iyun",
"iyul", "avgust", "sentabr", "oktabr", "noyabr", "dekabr")
return f"{x.day}-{OYLAR[x.month - 1]} {x.year}"
@ozbekcha.register
def _(x: type(None)) -> str:
return "yo'q"
SINOVLAR = [5, 1234567, 3.14159, "salom", True, False, None,
[1, 2, 3], ("a", "b"), {"x": 1, "y": True},
date(2026, 3, 15), Decimal("1.5")]
print(f" {'Kirish':<28} {'Tur':<12} {'Natija'}")
print(" " + "─" * 62)
for x in SINOVLAR:
print(f" {x!r:<28} {type(x).__name__:<12} {ozbekcha(x)}")
print(f"\n Ro'yxatga olingan turlar:")
print(f" {sorted(t.__name__ for t in ozbekcha.registry)}")
print(f"""
⭐ E'TIBOR BERING:
• bool int dan OLDIN tekshiriladi (aniqroq tur)
• Decimal ro'yxatda yo'q → sukut ishladi
• list va tuple bir funksiyaga bog'landi
• Rekursiv chaqiruv ishlaydi (list ichida dict)
""")
class Formatlagich:
"""singledispatchmethod — metodlar uchun."""
def __init__(self, prefiks: str = "→"):
self.prefiks = prefiks
@singledispatchmethod
def formatla(self, x) -> str:
return f"{self.prefiks} {x!r}"
@formatla.register
def _(self, x: int) -> str:
return f"{self.prefiks} son: {x:,}"
@formatla.register
def _(self, x: list) -> str:
return f"{self.prefiks} [{len(x)} element]"
f = Formatlagich("»")
print(f" singledispatchmethod:")
for x in [42, [1, 2, 3], "abc"]:
print(f" {f.formatla(x)}")Natijaning muhim qismi:
=== 1. Dunder metodlar — o'rnatilgan polimorfizm ===
v1 + v2 → Vektor(5.0, 7.0, 9.0)
3 * v1 → Vektor(3.0, 6.0, 9.0)
v1 * v2 → 32.0
f'{v1:u}' → '3.7417'
sorted([v2, v1]) → [Vektor(1.0, 2.0, 3.0), Vektor(...)]
=== ⭐ 2. NotImplemented mexanizmi ===
Chap() + Ong():
Chap.__add__(Ong) chaqirildi
Ong.__radd__(Chap) chaqirildi
natija: 'Ong hal qildi'
Ota() + Bola() = 'Bola.__radd__' ⭐ avlod birinchi
=== 5. singledispatch ===
Kirish Tur Natija
──────────────────────────────────────────────────────────────
5 int besh
True bool ha
None NoneType yo'q
[1, 2, 3] list bir, ikki, uch
datetime.date(2026, 3, 15) date 15-mart 2026
Decimal('1.5') Decimal noma'lum tur: DecimalNima ko'rsatdi: 2.3, 2.6, 2.7-bo'limlar.
Misol 4 — Amaliy: eksport tizimi
"""Polimorfizmning barcha shakllari bir tizimda."""
from __future__ import annotations
import csv
import io
import json
from abc import ABC, abstractmethod
from dataclasses import dataclass, asdict, fields, is_dataclass
from datetime import date, datetime
from decimal import Decimal
from functools import singledispatch
from typing import Any, Protocol, runtime_checkable
print("=== EKSPORT TIZIMI ===\n")
# ═══ 1. PROTOCOL — kirish ma'lumoti ═══
@runtime_checkable
class Eksportlanadigan(Protocol):
"""⭐ Meros TALAB QILMAYDI."""
def lugat(self) -> dict[str, Any]: ...
# ═══ 2. ABC — chiqish formatlari ═══
class Eksportchi(ABC):
"""Chiqish formati uchun abstrakt asos."""
KENGAYTMA: str = ""
MIME: str = ""
@abstractmethod
def yoz(self, yozuvlar: list[dict]) -> str:
"""Yozuvlarni matnga o'giradi."""
def eksport(self, obyektlar) -> str:
"""⭐ Sukut amalga oshirish — barcha avlodlar uchun."""
yozuvlar = [self._lugatga(o) for o in obyektlar]
return self.yoz(yozuvlar)
@staticmethod
def _lugatga(o) -> dict:
"""⭐ Duck typing — turli manbalarni qabul qiladi."""
if isinstance(o, dict):
return dict(o)
if is_dataclass(o) and not isinstance(o, type):
return asdict(o)
if hasattr(o, "lugat"):
return o.lugat()
if hasattr(o, "_asdict"): # NamedTuple
return o._asdict()
if hasattr(o, "__dict__"):
return {k: v for k, v in vars(o).items()
if not k.startswith("_")}
raise TypeError(f"Eksport qilib bo'lmaydi: {type(o).__name__}")
# ═══ 3. SINGLEDISPATCH — qiymatlarni o'girish ═══
@singledispatch
def qiymatga(x) -> Any:
"""JSON ga mos qiymatga o'giradi."""
return str(x)
@qiymatga.register
def _(x: int | float | bool | str | None) -> Any: # ⭐ union (3.11+)
return x
@qiymatga.register
def _(x: Decimal) -> float:
return float(x)
@qiymatga.register
def _(x: date | datetime) -> str:
return x.isoformat()
@qiymatga.register
def _(x: list | tuple) -> list:
return [qiymatga(e) for e in x]
@qiymatga.register
def _(x: dict) -> dict:
return {str(k): qiymatga(v) for k, v in x.items()}
@qiymatga.register
def _(x: set) -> list:
return sorted(qiymatga(e) for e in x)
# ═══ 4. AVLODLAR ═══
class JsonEksportchi(Eksportchi):
KENGAYTMA = ".json"
MIME = "application/json"
def __init__(self, otstup: int = 2):
self.otstup = otstup
def yoz(self, yozuvlar: list[dict]) -> str:
return json.dumps(
[{k: qiymatga(v) for k, v in y.items()} for y in yozuvlar],
ensure_ascii=False, indent=self.otstup,
)
class CsvEksportchi(Eksportchi):
KENGAYTMA = ".csv"
MIME = "text/csv"
def __init__(self, ajratgich: str = ","):
self.ajratgich = ajratgich
def yoz(self, yozuvlar: list[dict]) -> str:
if not yozuvlar:
return ""
chiqish = io.StringIO()
maydonlar = list(yozuvlar[0])
yozuvchi = csv.DictWriter(chiqish, maydonlar,
delimiter=self.ajratgich,
lineterminator="\n")
yozuvchi.writeheader()
for y in yozuvlar:
yozuvchi.writerow({k: qiymatga(v) for k, v in y.items()})
return chiqish.getvalue()
class MarkdownEksportchi(Eksportchi):
KENGAYTMA = ".md"
MIME = "text/markdown"
def yoz(self, yozuvlar: list[dict]) -> str:
if not yozuvlar:
return "*(bo'sh)*"
maydonlar = list(yozuvlar[0])
kenglik = {
m: max(len(str(m)), *(len(str(qiymatga(y.get(m, ""))))
for y in yozuvlar))
for m in maydonlar
}
qatorlar = [
"| " + " | ".join(f"{m:<{kenglik[m]}}" for m in maydonlar) + " |",
"|" + "|".join("-" * (kenglik[m] + 2) for m in maydonlar) + "|",
]
for y in yozuvlar:
qatorlar.append(
"| " + " | ".join(
f"{str(qiymatga(y.get(m, ''))):<{kenglik[m]}}"
for m in maydonlar
) + " |"
)
return "\n".join(qatorlar)
class MatnEksportchi(Eksportchi):
KENGAYTMA = ".txt"
MIME = "text/plain"
def yoz(self, yozuvlar: list[dict]) -> str:
qismlar = []
for i, y in enumerate(yozuvlar, 1):
qismlar.append(f"--- Yozuv {i} ---")
eng_uzun = max((len(k) for k in y), default=0)
for k, v in y.items():
qismlar.append(f" {k:<{eng_uzun}} : {qiymatga(v)}")
return "\n".join(qismlar)
# ═══ 5. TURLI MANBA TURLARI ═══
@dataclass
class Xodim:
"""dataclass — asdict() ishlatiladi."""
ism: str
lavozim: str
maosh: Decimal
ishga_kirgan: date
faol: bool = True
class Mijoz:
"""⭐ lugat() metodi — Protocol ga mos."""
def __init__(self, nom, email, buyurtmalar):
self.nom = nom
self.email = email
self._buyurtmalar = buyurtmalar
def lugat(self):
return {
"nom": self.nom,
"email": self.email,
"buyurtmalar": len(self._buyurtmalar),
"jami": sum(self._buyurtmalar),
}
class Mahsulot:
"""__dict__ ishlatiladi."""
def __init__(self, nom, narx, soni):
self.nom = nom
self.narx = narx
self.soni = soni
self._ichki = "chiqarilmaydi"
from typing import NamedTuple
class Buyurtma(NamedTuple):
"""NamedTuple — _asdict() ishlatiladi."""
raqam: int
sana: date
summa: Decimal
XODIMLAR = [
Xodim("Aziz Karimov", "Dasturchi", Decimal("8500000"),
date(2023, 3, 15)),
Xodim("Malika Yusupova", "Dizayner", Decimal("7000000"),
date(2024, 1, 10)),
Xodim("Bobur Aliyev", "Menejer", Decimal("9500000"),
date(2022, 6, 1), faol=False),
]
MIJOZLAR = [
Mijoz("Alfa MChJ", "info@alfa.uz", [1_000_000, 2_500_000]),
Mijoz("Beta LLC", "hi@beta.uz", [750_000]),
]
MAHSULOTLAR = [
Mahsulot("Klaviatura", 350_000, 12),
Mahsulot("Sichqoncha", 150_000, 30),
]
BUYURTMALAR = [
Buyurtma(1001, date(2026, 3, 1), Decimal("1250000")),
Buyurtma(1002, date(2026, 3, 5), Decimal("890000")),
]
LUGATLAR = [
{"kalit": "til", "qiymat": "python"},
{"kalit": "versiya", "qiymat": "3.12"},
]
print("1. ⭐ Protocol tekshiruvi:\n")
MANBALAR = [
("Xodim (dataclass)", XODIMLAR),
("Mijoz (lugat())", MIJOZLAR),
("Mahsulot (__dict__)", MAHSULOTLAR),
("Buyurtma (NamedTuple)", BUYURTMALAR),
("dict", LUGATLAR),
]
print(f" {'Manba':<26} {'Eksportlanadigan':<20} {'Usul'}")
print(" " + "─" * 62)
for nom, malumot in MANBALAR:
namuna = malumot[0]
mos = isinstance(namuna, Eksportlanadigan)
if isinstance(namuna, dict):
usul = "dict"
elif is_dataclass(namuna):
usul = "asdict()"
elif hasattr(namuna, "lugat"):
usul = "lugat()"
elif hasattr(namuna, "_asdict"):
usul = "_asdict()"
else:
usul = "__dict__"
print(f" {nom:<26} {str(mos):<20} {usul}")
print(f"\n ⭐ Faqat Mijoz Protocol ga mos, lekin HAMMASI eksport qilinadi")
print(f" (duck typing + tur bo'yicha shoxlanish)")
print("\n\n2. Turli formatlar:\n")
EKSPORTCHILAR = [
JsonEksportchi(otstup=None),
CsvEksportchi(),
MarkdownEksportchi(),
MatnEksportchi(),
]
for e in EKSPORTCHILAR:
natija = e.eksport(XODIMLAR)
print(f" ┌─ {type(e).__name__} ({e.MIME}) → *{e.KENGAYTMA}")
for q in natija.split("\n")[:6]:
print(f" │ {q[:70]}")
qolgan = len(natija.split("\n")) - 6
if qolgan > 0:
print(f" │ ... yana {qolgan} qator")
print(f" └{'─' * 66}\n")
print("3. ⭐ Bir eksportchi — barcha manbalar:\n")
md = MarkdownEksportchi()
for nom, malumot in MANBALAR:
print(f" {nom}:")
natija = md.eksport(malumot)
for q in natija.split("\n")[:4]:
print(f" {q}")
print()
print("4. singledispatch — qiymat o'girish:\n")
QIYMATLAR = [
42, 3.14, True, None, "matn",
Decimal("1234.56"), date(2026, 3, 15),
datetime(2026, 3, 15, 14, 30),
[1, Decimal("2.5"), date(2026, 1, 1)],
{"a": Decimal("1"), "b": [date(2026, 1, 1)]},
{3, 1, 2},
]
print(f" {'Kirish':<40} {'Chiqish'}")
print(" " + "─" * 68)
for q in QIYMATLAR:
print(f" {q!r:<40} {qiymatga(q)!r}")
print(f"\n Ro'yxatga olingan turlar ({len(qiymatga.registry)}):")
print(f" {sorted(t.__name__ for t in qiymatga.registry)}")
print("\n\n5. Yangi format qo'shish:\n")
class YamlEksportchi(Eksportchi):
"""⭐ Mavjud kodni O'ZGARTIRMASDAN qo'shildi."""
KENGAYTMA = ".yml"
MIME = "application/yaml"
def yoz(self, yozuvlar: list[dict]) -> str:
qatorlar = []
for y in yozuvlar:
qatorlar.append("-")
for k, v in y.items():
q = qiymatga(v)
if isinstance(q, str) and (" " in q or ":" in q):
q = f'"{q}"'
qatorlar.append(f" {k}: {q}")
return "\n".join(qatorlar)
print(f" YamlEksportchi (yangi):")
for q in YamlEksportchi().eksport(XODIMLAR[:2]).split("\n"):
print(f" {q}")
print("\n\n6. Yangi manba turi qo'shish:\n")
class Filial:
"""⭐ Yangi tur — hech narsa o'zgartirilmadi."""
def __init__(self, shahar, xodimlar, aylanma):
self.shahar = shahar
self.xodimlar = xodimlar
self.aylanma = aylanma
def lugat(self):
return {"shahar": self.shahar, "xodimlar": self.xodimlar,
"aylanma": self.aylanma}
FILIALLAR = [
Filial("Toshkent", 45, Decimal("1250000000")),
Filial("Samarqand", 18, Decimal("430000000")),
]
print(f" isinstance(Filial(...), Eksportlanadigan) = "
f"{isinstance(FILIALLAR[0], Eksportlanadigan)} ✅\n")
for q in MarkdownEksportchi().eksport(FILIALLAR).split("\n"):
print(f" {q}")
print("\n\n7. Xato holatlar:\n")
class Yaroqsiz:
__slots__ = () # __dict__ yo'q
for obj in [Yaroqsiz(), 42, "satr"]:
try:
JsonEksportchi().eksport([obj])
natija = "⚠️ o'tdi"
except TypeError as e:
natija = f"✅ TypeError: {e}"
print(f" {type(obj).__name__:<12} {natija}")
print(f"""
⭐ BU TIZIMDA POLIMORFIZMNING TO'RT SHAKLI:
1. DUCK TYPING (_lugatga)
Turli obyektlarni bir xil qabul qiladi
2. SUBTIP (Eksportchi ABC)
Har format — Eksportchi ning avlodi
eksport() bir marta yozilgan
3. AD-HOC (singledispatch)
qiymatga() — tur bo'yicha turli amalga oshirish
4. STRUKTURAVIY (Protocol)
Eksportlanadigan — meros talab qilmaydi
⭐ NATIJA:
• Yangi FORMAT qo'shish → yangi Eksportchi avlodi
• Yangi MANBA turi qo'shish → lugat() metodi yetadi
• Yangi QIYMAT turi qo'shish → @qiymatga.register
Har uchalasi ham MAVJUD KODNI O'ZGARTIRMAYDI.
""")Natijaning muhim qismi:
1. ⭐ Protocol tekshiruvi:
Manba Eksportlanadigan Usul
──────────────────────────────────────────────────────────────
Xodim (dataclass) False asdict()
Mijoz (lugat()) True lugat()
Mahsulot (__dict__) False __dict__
Buyurtma (NamedTuple) False _asdict()
2. Turli formatlar:
┌─ CsvEksportchi (text/csv) → *.csv
│ ism,lavozim,maosh,ishga_kirgan,faol
│ Aziz Karimov,Dasturchi,8500000.0,2023-03-15,True
┌─ MarkdownEksportchi (text/markdown) → *.md
│ | ism | lavozim | maosh | ...
│ |-----------------|-----------|-----------|...
4. singledispatch — qiymat o'girish:
Decimal('1234.56') 1234.56
datetime.date(2026, 3, 15) '2026-03-15'
{1, 2, 3} [1, 2, 3]Nima ko'rsatdi: 2.2, 2.4, 2.5, 2.7-bo'limlar.
5. To'g'ri va noto'g'ri tushunishlar
| Noto'g'ri fikr | To'g'risi |
|---|---|
| "Polimorfizm meros talab qiladi" | Pythonda duck typing yetadi |
"Protocol — ABC ning sinonimi" |
Meros talab qilmaydi, statik tekshiriladi |
"isinstance + Protocol — to'liq tekshiruv" |
Faqat nom, imzo emas |
"register() metodlarni tekshiradi" |
Hech narsa tekshirmaydi |
"NotImplemented — istisno" |
Qiymat (singleton) |
"NotImplementedError ni __eq__ da tashlash mumkin" |
Dasturni buzadi |
"singledispatch — Java overloading" |
Faqat birinchi argument bo'yicha |
| "Duck typing xavfsiz" | Nom mos, ma'no boshqa bo'lishi mumkin |
6. Keng tarqalgan xatolar va yechimlari
1. isinstance bilan shoxlanish
if isinstance(s, Doira): ... # ⚠️
return s.yuza() # ✅2. NotImplementedError ni __eq__ da
def __eq__(self, b):
raise NotImplementedError # ⚠️
return NotImplemented # ✅3. __radd__ unutish
def __mul__(self, b): ... # ⚠️ 3 * v ishlamaydi
def __rmul__(self, b): # ✅
return self.__mul__(b)4. register() ga ishonish
Shakl.register(Yolgon) # ⚠️ tekshirmaydi
class Yolgon(Shakl): ... # ✅ yoki __subclasshook__5. Protocol da @runtime_checkable unutish
class P(Protocol): ...
isinstance(x, P) # ❌ TypeError
@runtime_checkable # ✅
class P(Protocol): ...6. singledispatch da bool va int tartibi
@f.register
def _(x: int): ... # bool ham int
@f.register
def _(x: bool): ... # ✅ aniqroq tur ustuvor7. hasattr bilan ortiqcha tekshiruv
if hasattr(x, "f") and callable(x.f): # ⚠️ LBYL
try: x.f() # ✅ EAFP
except AttributeError: ...8. __hash__ unutish
def __eq__(self, b): ... # ⚠️ __hash__ = None bo'ladi
def __hash__(self): return hash(...) # ✅7. Integratsiya — bu bilim qayerda kerak bo'ladi
- 8.6-8.8-darslar (o'tilgan): meros — subtip polimorfizmi
- 8.11-8.14: dunder metodlar — to'liq
- 8.18: ABC va
collections.abc - 7.14 (o'tilgan):
Protocolva tur ko'rsatkichlari - 15-qism:
functools—singledispatch,total_ordering - 20, 23-qismlar: ORM va API — duck typing amalda
- PEP 544: Protocols; PEP 3119: ABC
8. Eng yaxshi amaliyotlar
Duck typing — sukut tanlov.
isinstancefaqat chegarada.Interfeys uchun
Protocol. Tashqi sinflar bilan ishlaganda.Sukut amalga oshirish kerak bo'lsa — ABC. O'z ierarxiyangizda.
NotImplementedqaytaring, tashlamang. Ikkilamchi amallarda.__r*__juftlarini yozing.__add__/__radd__,__mul__/__rmul__.__eq__bilan__hash__. Ikkalasi birga.EAFP, LBYL emas.
try/except,hasattrzanjiri emas.mypybilan tekshiring. Duck typing xatolarini erta topadi.
9. Amaliy topshiriq
Vazifa 1: Natijani bashorat qiling
1. class A:
def __add__(self, b): return NotImplemented
class B:
def __radd__(self, b): return "B"
print(A() + B())
2. class A:
def __eq__(self, b): return NotImplemented
print(A() == 42)
3. from typing import Protocol, runtime_checkable
@runtime_checkable
class P(Protocol):
def f(self): ...
class X:
def f(self, a, b): ...
print(isinstance(X(), P))
4. from abc import ABC, abstractmethod
class A(ABC):
@abstractmethod
def f(self): ...
class B(A): pass
try: B()
except TypeError: print("xato")
5. from functools import singledispatch
@singledispatch
def f(x): return "sukut"
@f.register
def _(x: int): return "int"
print(f(True))
6. class A:
def __len__(self): return 0
print(bool(A()))
7. class A:
def __getitem__(self, i):
if i > 2: raise IndexError
return i
print(list(A()))
8. class A:
def __eq__(self, b): return True
print(hash(A()) if A().__hash__ else "hash yo'q")
9. from abc import ABC
class A(ABC): pass
class B: pass
A.register(B)
print(issubclass(B, A), B.__mro__)
10. class A:
def __add__(self, b): return "A"
class B(A):
def __radd__(self, b): return "B"
print(A() + B())
11. from collections.abc import Sized
print(isinstance("ab", Sized), isinstance(42, Sized))
12. print(NotImplemented is NotImplementedError)Javoblar
B—__radd__ga o'tdiFalse— Pythonisbilan solishtiradiTrue— imzo tekshirilmaydixato— abstrakt metod amalga oshirilmaganint—boolintning avlodiFalse—__len__0qaytardi[0, 1, 2]—__getitem__dan iteratsiyahash yo'q—__eq____hash__niNoneqiladiTrue (<class '__main__.B'>, <class 'object'>)B— avlod__radd__birinchiTrue FalseFalse— turli obyektlar
Vazifa 2: Xatolarni tuzating
1. def __eq__(self, b):
raise NotImplementedError
2. def __mul__(self, b): return ... # 3 * v kerak
3. class P(Protocol): ...
isinstance(x, P)
4. if isinstance(s, Doira): return 3.14 * s.r**2
elif isinstance(s, Kvadrat): return s.a**2
5. class A:
def __eq__(self, b): return self.x == b.x
6. @singledispatch
def f(x): ...
@f.register
def _(x: int): ...
# bool uchun boshqa xatti-harakat kerak
7. if hasattr(x, "f") and callable(getattr(x, "f")): x.f()
8. Shakl.register(Yolgon) # Yolgon da yuza() yo'qJavoblar
1. return NotImplemented
2. __rmul__ qo'shing
3. @runtime_checkable dekoratori
4. return s.yuza() — polimorfizm
5. __hash__ ham qo'shing, isinstance tekshiruvi bilan
6. @f.register def _(x: bool): ... qo'shing
7. try: x.f() except AttributeError: ...
8. Meros oling yoki __subclasshook__ ishlatingVazifa 3: Shakl tizimi
Yozing:
Shakl—Protocol(yuza,perimetr)- 5 xil shakl — meros olmasdan
AsosShakl(ABC)— sukut metodlar bilan- Ba'zi shakllar ABC dan meros olsin, ba'zilari yo'q
- Umumiy funksiyalar ikkalasi bilan ham ishlasin
mypy --stricttoza o'tsin
Vazifa 4: Pul sinfi
__add__,__sub__,__mul__,__truediv__- Har biri uchun
__r*__versiyasi - Turli valyutalarda
ValueError NotImplementedto'g'ri ishlatilsintotal_orderingbilan taqqoslash__format__— turli formatlar ('.2f','sozlar')
Vazifa 5: singledispatch bilan validator
@singledispatch def tekshir(x) -> list[str]int,str,list,dict,dateuchun qoidalar- Ichma-ich tuzilmalarni rekursiv tekshirsin
- Xato yo'llarini ko'rsatsin (
data.users[0].email) - Yangi tur qo'shish oson bo'lsin
Protocolbilan maxsus turlarni qo'llab-quvvatlasin
Vazifa 6: Duck typing detektori
Vosita yozing:
- Modulda bir xil nomli metodlarni topsin
- Ularning imzolarini solishtirsin
- Mos kelmasa ogohlantirsin
Protocolyaratishni taklif qilsinisinstancebilan shoxlanishni topsin- Polimorfizmga o'girish taklifi
Vazifa 7: O'ylash
Nega Python Protocol ni qo'shdi, agar duck typing allaqachon ishlagan bo'lsa?
Javob
Chunki duck typing ish vaqtida ishlaydi, lekin katta kod bazasida xatolarni faqat ishlab chiqarishda ko'rsatadi.
1. Duck typing muammosi
def ishla(ombor):
ombor.saqla("kalit", "qiymat")
return ombor.olish("kalit")Savollar, javobsiz:
omborqanday interfeysga ega bo'lishi kerak?saqlaqanday argumentlar oladi?olishnima qaytaradi?- Xato bo'lsa nima tashlaydi?
Javob faqat kodni o'qish yoki ishga tushirish bilan bilinadi.
2. Muammo katta loyihada o'sadi
Dropbox (4 million qator Python) tur ko'rsatkichlariga o'tishdan oldingi holat:
- Bir metod nomi 20 joyda, turli imzolar bilan
- "Bu funksiyaga nima uzatiladi?" — kod arxeologiyasi
- Refaktoring xavfli — nima buzilishini bilib bo'lmaydi
- IDE avtoto'ldirish ishlamaydi
3. Birinchi urinish — ABC (Python 2.6, PEP 3119)
from abc import ABC, abstractmethod
class Ombor(ABC):
@abstractmethod
def saqla(self, k: str, v: str) -> None: ...
@abstractmethod
def olish(self, k: str) -> str | None: ...
class FaylOmbor(Ombor): # ⚠️ MEROS majburiy
...Muammolar:
# 1. Tashqi sinflarni o'zgartirib bo'lmaydi
class UchinchiTomonOmbor: # boshqa kutubxonadan
def saqla(self, k, v): ...
def olish(self, k): ...
Ombor.register(UchinchiTomonOmbor) # ⚠️ tekshirmaydi
# 2. Meros bog'lanish yaratadi
class MeningOmborim(Ombor): # ⚠️ endi Ombor ga bog'liq
# 3. Ko'p interfeys → ko'p meros
class X(Oquvchi, Yozuvchi, Yopiladigan, Iterlanadigan): ...
# 4. Ish vaqtida narx
isinstance(x, Ombor) # ABCMeta.__instancecheck__ — sekin4. Protocol — yechim (PEP 544, Python 3.8)
from typing import Protocol
class Ombor(Protocol):
def saqla(self, k: str, v: str) -> None: ...
def olish(self, k: str) -> str | None: ...
def ishla(ombor: Ombor) -> str | None:
ombor.saqla("k", "v")
return ombor.olish("k")
class UchinchiTomonOmbor: # ⭐ meros YO'Q, o'zgartirish YO'Q
def saqla(self, k: str, v: str) -> None: ...
def olish(self, k: str) -> str | None: ...
ishla(UchinchiTomonOmbor()) # ✅ mypy ham roziBu — "strukturaviy tiplash" (structural typing) yoki "statik duck typing".
5. Ikki tiplash tizimi
| Nominal | Strukturaviy | |
|---|---|---|
| Mos kelish sharti | Nom (meros) | Tuzilma (metodlar) |
| Tillar | Java, C#, C++ | Go, TypeScript, OCaml |
| Pythonda | ABC | Protocol |
# Nominal — nom bo'yicha
class A(Ombor): ... # "men Ombor man" deb E'LON qiladi
# Strukturaviy — tuzilma bo'yicha
class A:
def saqla(...): ... # "men Ombor kabi ko'rinaman"
def olish(...): ...Go tilida faqat strukturaviy:
type Ombor interface {
Saqla(k, v string)
Olish(k string) string
}
type MeningOmborim struct{} // interface ni E'LON QILMAYDI
func (m MeningOmborim) Saqla(k, v string) {}
func (m MeningOmborim) Olish(k string) string { return "" }
// ✅ Avtomatik mos keladiTypeScript ham strukturaviy:
interface Ombor {
saqla(k: string, v: string): void;
}
const x = { saqla(k: string, v: string) {} };
const o: Ombor = x; // ✅ interface e'lon qilinmagan6. Protocol nima beradi
from typing import Protocol
class Ombor(Protocol):
def saqla(self, k: str, v: str) -> None: ...a) Hujjat
Funksiya imzosi endi nimani kutayotganini aytadi:
def ishla(o: Ombor): ... # ⭐ aniq
def ishla(o): ... # ⚠️ noaniqb) Statik tekshiruv
class Yolgon:
def saqla(self, k): ... # ⚠️ v yo'q
ishla(Yolgon())
# mypy: Argument 1 to "ishla" has incompatible type "Yolgon";
# expected "Ombor" ABC va isinstance buni topa olmaydi — imzoni tekshirmaydi.
c) IDE yordami
def ishla(o: Ombor):
o.<TAB> # ⭐ saqla, olish taklif qilinadid) Refaktoring xavfsizligi
Protokolga metod qo'shsangiz — mypy barcha amalga oshirishlarni tekshiradi.
e) Sukut amalga oshirish (3.8+)
class Ombor(Protocol):
def saqla(self, k: str, v: str) -> None: ...
def kop_saqla(self, juftlar: dict[str, str]) -> None:
"""⭐ Sukut — meros olganlar ishlatadi."""
for k, v in juftlar.items():
self.saqla(k, v)7. Ish vaqtida ham kerak bo'lsa
from typing import Protocol, runtime_checkable
@runtime_checkable
class Ombor(Protocol):
def saqla(self, k: str, v: str) -> None: ...
isinstance(x, Ombor) # ✅ ishlaydiLekin faqat nom tekshiriladi:
class Yolgon:
saqla = "bu satr" # ⚠️ callable emas
isinstance(Yolgon(), Ombor) # ⚠️ 3.12+ da False, oldin True3.12 da yaxshilandi, lekin imzo hali ham tekshirilmaydi.
8. Standart kutubxonadagi protokollar
Python 3.8+ da ko'p joyda ishlatiladi:
from typing import (SupportsInt, SupportsFloat, SupportsIndex,
SupportsAbs, SupportsRound, SupportsBytes,
SupportsComplex)
class SupportsInt(Protocol):
def __int__(self) -> int: ...
def f(x: SupportsInt) -> int:
return int(x) # ✅ __int__ bor deb kafolatlangancollections.abc ham ko'pincha Protocol kabi ishlatiladi:
from collections.abc import Iterable, Sequence, Mapping
def f(x: Iterable[int]) -> list[int]: # ✅ eng umumiy
return sorted(x)9. Qachon qaysi
# ⭐ Protocol — tashqi kod, kengaytiriladigan
class Yozuvchi(Protocol):
def yoz(self, m: bytes) -> int: ...
def saqla(f: Yozuvchi, m: bytes): ...
# ✅ open(), io.BytesIO(), socket, sizning sinfingiz — hammasi mos
# ⭐ ABC — o'z ierarxiyangiz, sukut kod
class AsosHandler(ABC):
@abstractmethod
def ishla(self, s): ...
def oldindan(self, s): # umumiy kod
return self.ishla(self._tayyorla(s))
# ⭐ IKKALASI
class Ombor(Protocol): # tashqi API uchun
def saqla(self, k, v): ...
class AsosOmbor(ABC): # o'z avlodlaringiz uchun
@abstractmethod
def saqla(self, k, v): ...
def kop_saqla(self, d): ... # umumiy kod10. Xulosa: nega ikkalasi ham kerak
Protocol duck typing ni almashtirmadi — u unga statik qatlam qo'shdi:
| Duck typing | Protocol | ABC | |
|---|---|---|---|
| Moslashuvchanlik | Maksimal | Yuqori | Meros kerak |
| Hujjat | |||
| Statik tekshiruv | Qisman | ||
| IDE yordami | |||
| Sukut kod | Cheklangan | ||
| Ish vaqti narxi | Yo'q | Yo'q | Bor |
Pythonning falsafasi: har qatlam ixtiyoriy.
# 1. Hech narsa — eng oddiy
def f(x): return x.metod()
# 2. + hujjat
def f(x):
"""x — metod() ga ega bo'lsin."""
return x.metod()
# 3. + Protocol (statik)
def f(x: Metodli) -> str:
return x.metod()
# 4. + ish vaqtida tekshiruv
def f(x: Metodli) -> str:
if not isinstance(x, Metodli):
raise TypeError(...)
return x.metod()Siz kerakli darajani tanlaysiz. Kichik skriptda 1-daraja, kutubxonada 3-daraja, tashqi ma'lumot bilan ishlaganda 4-daraja.
Bu — Pythonning odatiy yondashuvi: tilni o'zgartirmasdan, ixtiyoriy qatlam qo'shish (mypy, dataclass, Protocol — hammasi shunday).
Nimani mustahkamlaydi: 2.2, 2.4, 2.5-bo'limlar.
Xulosa
Bu darsda polimorfizmning barcha shakllarini o'rgandik.
Eng muhim uch fikr:
Pythonda polimorfizm meros talab qilmaydi. Duck typing — asosiy mexanizm: obyektda kerakli metod bo'lsa yetadi. Bu testlashni osonlashtiradi (soxta obyekt — oddiy sinf), yangi turlarni mavjud kodni o'zgartirmasdan qo'shishga imkon beradi va EAFP uslubini tabiiy qiladi.
Protocol— duck typing ning statik shakli. U meros talab qilmaydi, lekinmypyga interfeysni tekshirish imkonini beradi — imzolar bilan birga. ABC esa meros talab qiladi, ammo sukut amalga oshirish bera oladi va ish vaqtida majburlaydi. Ikkalasi bir loyihada birga ishlatilishi normal.NotImplemented— qiymat,NotImplementedError— istisno. Ikkilamchi amalda (__add__,__eq__)NotImplementedqaytarilsa, Python teskari amalni (__radd__) sinaydi va faqat u ham rad etsaTypeErrorberadi.NotImplementedErrortashlash esa bu mexanizmni buzadi va dasturni to'xtatadi.
Keyingi darsda kapsulatsiyani ko'ramiz: _ va __ prefikslari, nom buzilishi (name mangling) va Pythonda "xususiy" nima degani.
Izohlar · 0
Izoh yozish uchun kiring.