классы, дескрипторы, дандер-методыclasses, descriptors, dunder methods

ООП в Pythonin Python

В отличие от Rust/Go, в Python есть настоящие классы и наследование (включая множественное, с MRO по C3-линеаризации) — но ряд механизмов устроен нестандартно: перегрузки методов по сигнатуре нет вообще, различие Unlike Rust/Go, Python has real classes and inheritance (including multiple inheritance, with MRO via C3 linearization) — but several mechanisms work differently from the classic OOP languages: there's no method overloading by signature at all, the __new__ и vs __init__ путают почти всех, а свойства (property) — полноценная языковая фича, а не заглушка. Раздел раскладывает 14 базовых концепций ООП плюс полиморфизм на реальную семантику Python — из них не попали в список события и константы, у которых в Python нет обеспеченного языком аналога. Каркас: 17 карточек, страницы ещё не написаны. Дополняет python/language/, где декораторы/dataclasses/метаклассы уже описаны на уровне фич языка — здесь тот же материал разложен по рамке классического ООП. split trips up almost everyone, and properties are a first-class language feature rather than a stand-in. This section maps the 14 baseline OOP concepts plus polymorphism onto Python's real semantics — 2 of the baseline concepts, events and constants, are missing since Python has no language-enforced analog for either. Skeleton: 17 cards, pages not yet written. Complements python/language/, which already covers decorators/dataclasses/metaclasses at the language-feature level — this section reframes the same material through the classic-OOP lens.

Базовые концепции ООПBaseline OOP concepts

Определение классов, инициализацияClass definition & initializationclass Foo: + + __init__ — тело класса выполняется один раз при импорте, создавая namespace класса. — the class body executes once at import time, building the class's namespace.interview КонструкторыConstructors__new__ vs vs __init__ — настоящий конструктор, создающий объект, это — the actual constructor that creates the instance is __new__, а , while __init__ лишь инициализирует уже созданный объект. only initializes an object that already exists.interview ДеструкторыDestructors__del__ — вызывается при сборке мусора объекта, но момент и сам факт вызова не гарантированы (в отличие от RAII в C++), полагаться на него для освобождения ресурсов нельзя. — runs when the object is garbage-collected, but neither the timing nor the fact of the call is guaranteed (unlike C++ RAII); don't rely on it for resource cleanup.interview ПоляFieldsатрибуты экземпляра задаются в instance attributes are set in __init__; модификаторов доступа нет — ; there are no access modifiers — _foo/__foo лишь соглашение (name mangling для двойного подчёркивания — не настоящая приватность). are only conventions (name mangling for double underscore isn't real privacy).interview МетодыMethodsобычные методы (self), instance methods (self), @classmethod (cls), (cls), @staticmethod — три разных способа биндинга. — three different binding strategies. Сигнатуры и перегрузкаSignatures & overloadingперегрузки методов по сигнатуре нет — на одно имя одна реализация; эмулируется значениями по умолчанию, no overloading by signature — one name, one implementation; emulated with default arguments, *args/**kwargs или , or @singledispatchmethod.interview СвойстваProperties@property / / @x.setter — полноценная языковая фича, а не эмуляция: доступ к вычисляемому значению выглядит как доступ к обычному полю. — a genuine first-class feature, not an emulation: access to a computed value looks like access to a plain field.interview ИндексаторыIndexers__getitem__/__setitem__/__delitem__ — те же дандеры делают объект и итерируемым, и slice-совместимым. — the same dunders also make an object iterable and slice-compatible. НаследованиеInheritanceнастоящее множественное наследование, порядок разрешения методов (MRO) по алгоритму C3-линеаризации, real multiple inheritance, method resolution order (MRO) via C3 linearization, super() следует MRO, а не жёстко зовёт родителя. follows the MRO rather than hard-calling a specific parent.interview ПолиморфизмPolymorphismутиная типизация — полиморфизм без общего базового класса, любой объект с нужным методом подходит; duck typing — polymorphism with no shared base class required, any object with the right method qualifies; ABC/Protocol формализуют контракт, когда нужна проверка. formalize the contract when you need one enforced.interview Вложенные классыNested classesclass Outer: class Inner: ... — синтаксис есть, но идиоматически используется редко, обычно предпочитают модульный namespace. — the syntax exists but is rarely idiomatic; a module-level namespace is usually preferred instead. Копирование объектовCopying objectscopy.copy() (поверхностное) vs (shallow) vs copy.deepcopy() (глубокое), хуки (deep), the __copy__/__deepcopy__ для кастомизации. hooks for customizing the behavior.interview Члены типаType membersатрибуты уровня класса разделяются между всеми экземплярами — частая грабля: изменяемое значение по умолчанию (список/словарь) на уровне класса становится общим состоянием.class-level attributes are shared across all instances — a common gotcha: a mutable class-level default (a list/dict) becomes shared state.interview

Специфика PythonPython-specific

то, на чём держится почти всё остальноеwhat almost everything else is built on
Дандер-методыDunder / magic methods__eq__, __repr__, __len__ и другие — фактический механизм почти всего в этом списке: перегрузка операторов, индексация, копирование, представление объекта., and others — the actual mechanism behind almost everything on this page: operator overloading, indexing, copying, object representation.interview Duck typing и структурная типизацияDuck typing & structural typingABC и and typing.Protocol формализуют «если крякает как утка» — номинальная и структурная проверка типов бок о бок. formalize "if it quacks like a duck" — nominal and structural type checking side by side.interview МетаклассыMetaclassestype как метакласс по умолчанию, кастомный метакласс перехватывает создание класса; as the default metaclass, a custom metaclass hooks class creation; __init_subclass__ — более лёгкая альтернатива для большинства случаев. is a lighter alternative that covers most use cases. Dataclasses@dataclass автогенерирует auto-generates __init__/__eq__/__repr__ по аннотациям полей — см. карточку dataclasses в python/language/ для деталей на уровне фичи языка. from field annotations — see the dataclasses card in python/language/ for the language-feature-level detail.

статусstatus

Это каркас: 2 подраздела и 17 карточек зафиксированы, страницы ещё не написаны. К 14 базовым концепциям ООП добавлен полиморфизм (утиная типизация, ABC/Protocol); событий и констант в списке нет — в Python нет для них обеспеченного языком аналога (только соглашения). Метка interview отмечает самые частые темы на собеседованиях: различие __new__/__init__, свойства, дандер-методы, MRO/множественное наследование, полиморфизм через duck typing, грабля с изменяемым значением по умолчанию.This is a skeleton: 2 subsections and 17 cards are locked in, pages not yet written. Polymorphism (duck typing, ABC/Protocol) was added to the 14 baseline OOP concepts; events and constants are missing from the list since Python has no language-enforced analog for either (only conventions). The interview tag marks the most common interview topics: the __new__/__init__ split, properties, dunder methods, MRO/multiple inheritance, duck-typing polymorphism, the mutable-default-argument gotcha.