Asosiy matnga o'tish
ITIT Interview
Python

Dunder metodlar

Maxsus (magic) metodlar, __repr__ va __str__, __eq__ va __hash__, operatorlarni qayta yuklash, __len__ va __getitem__, __call__, __new__ va __slots__.

O'rganildi: 0 / 5
Progress

Bu nima?

Dunder (double underscore) yoki magic metodlar — __nomi__ ko'rinishidagi maxsus metodlar. Python ularni o'rnatilgan amallar uchun avtomatik chaqiradi: len(x) → x.__len__(), a + b → a.__add__(b). Ular yordamida o'z klasslaringizni o'rnatilgan turlar kabi ishlatish mumkin.

Asosiy dunder metodlar

MetodQachon chaqiriladi
__init__Obyekt yaratilgandan keyin (initsializatsiya)
__new__Obyektni yaratishda, __init__ dan oldin
__repr__repr(x), konsolda, debug
__str__str(x), print(x), f-string
__eq__, __lt__==, <
__hash__hash(x), dict kaliti, set
__len__len(x)
__getitem__x[key]
__contains__item in x
__iter__, __next__for sikli
__call__x() — obyektni funksiya kabi chaqirish
__enter__, __exit__with bloki
__add__, __mul__+, *
__bool__if x:

__repr__ va __str__

class Money:
    def __init__(self, amount, currency="UZS"):
        self.amount = amount
        self.currency = currency

    def __repr__(self):                 # dasturchi uchun, aniq
        return f"Money({self.amount!r}, {self.currency!r})"

    def __str__(self):                  # foydalanuvchi uchun, chiroyli
        return f"{self.amount:,} {self.currency}"

m = Money(150000)
print(m)    # 150,000 UZS
m           # Money(150000, 'UZS')

__str__ bo'lmasa __repr__ ishlatiladi, shuning uchun kamida __repr__ ni yozing.

Operatorlarni qayta yuklash

class Money:
    ...
    def __add__(self, other):
        if not isinstance(other, Money):
            return NotImplemented          # Python boshqa usulni sinab ko'radi
        if other.currency != self.currency:
            raise ValueError("Valyutalar har xil")
        return Money(self.amount + other.amount, self.currency)

    def __eq__(self, other):
        return isinstance(other, Money) and (self.amount, self.currency) == (other.amount, other.currency)

    def __hash__(self):
        return hash((self.amount, self.currency))

Money(100) + Money(50)    # Money(150, 'UZS')

__eq__ yozilsa, __hash__ avtomatik None bo'ladi va obyekt hashable bo'lmay qoladi. Teng obyektlarning hash'i ham teng bo'lishi shart.

Konteyner protokoli

class Playlist:
    def __init__(self, songs):
        self._songs = list(songs)

    def __len__(self):
        return len(self._songs)

    def __getitem__(self, index):       # indeks, slicing va for sikli ishlaydi
        return self._songs[index]

    def __contains__(self, song):
        return song in self._songs

p = Playlist(["A", "B", "C"])
len(p), p[0], p[1:], "B" in p

__call__

class RateLimiter:
    def __init__(self, limit):
        self.limit = limit
        self.calls = 0

    def __call__(self):
        self.calls += 1
        return self.calls <= self.limit

allow = RateLimiter(3)
allow()   # True

__new__ va __slots__

class Singleton:
    _instance = None
    def __new__(cls, *args, **kwargs):     # obyektni yaratadi va qaytaradi
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

class Point:
    __slots__ = ("x", "y")                 # __dict__ siz — kamroq xotira, tezroq atributlar
    def __init__(self, x, y):
        self.x, self.y = x, y

Intervyu savollari

Ushbu sahifada