Text of docs.python.org › uk › 3 › howto › descriptor.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

Descriptor Guide — Python 3.15.2 documentation

Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » Python HOWTO » Descriptor Guide | Theme | Descriptor Guide ¶ Дескриптори дозволяють об’єктам налаштовувати пошук атрибутів, зберігання та видалення. Цей посібник складається з чотирьох основних розділів: «Буквар» дає базовий огляд, обережно переходячи від простих прикладів, додаючи одну функцію за раз.

Почніть тут, якщо ви новачок у дескрипторах. Другий розділ показує повний, практичний приклад дескриптора. Якщо ви вже знаєте основи, почніть з цього. Третій розділ містить більш технічний підручник, який детально описує механізм роботи дескрипторів.

Більшості людей не потрібен такий рівень деталізації. The last section has pure Python equivalents for built-in descriptors that are written in C. Read this if you’re curious about how functions turn into bound methods or about the implementation of common tools like @classmethod , @staticmethod , @property , and __slots__ . Буквар ¶ У цьому посібнику ми починаємо з найпростішого можливого прикладу, а потім будемо додавати нові можливості одну за одною.

Простий приклад: дескриптор, який повертає константу ¶ The Ten class is a descriptor whose __get__() method always returns the constant 10 : class Ten : def __get__ ( self , obj , objtype = None ): return 10 Щоб використовувати дескриптор, його потрібно зберегти як змінну класу в іншому класі: class A : x = 5 # Regular class attribute y = Ten () # Descriptor instance Інтерактивний сеанс показує різницю між звичайним пошуком атрибута та пошуком дескриптора: >>> a = A () # Make an instance of class A >>> a . x # Normal attribute lookup 5 >>> a . y # Descriptor lookup 10 Під час пошуку атрибутів a.x оператор крапки знаходить 'x': 5 у словнику класу.

Під час пошуку a.y оператор точки знаходить екземпляр дескриптора, розпізнаний його методом __get__ . Виклик цього методу повертає 10 . Зверніть увагу, що значення 10 не зберігається ні в словнику класу, ні в словнику екземпляра. Натомість значення 10 обчислюється на вимогу.

Цей приклад показує, як працює простий дескриптор, але він не дуже корисний. Для отримання констант кращим буде звичайний пошук атрибутів. У наступному розділі ми створимо щось більш корисне, динамічний пошук. Динамічні пошуки ¶ Цікаві дескриптори зазвичай запускають обчислення замість повернення констант: import os class DirectorySize : def __get__ ( self , obj , objtype = None ): return len ( os . listdir ( obj . dirname )) class Directory : size = DirectorySize () # Descriptor instance def __init__ ( self , dirname ): self . dirname = dirname # Regular instance attribute Інтерактивний сеанс показує, що пошук є динамічним — він щоразу обчислює різні оновлені відповіді: >>> s = Directory ( 'songs' ) >>> g = Directory ( 'games' ) >>> s . size # The songs directory has twenty files 20 >>> g . size # The games directory has three files 3 >>> os . remove ( 'games/chess' ) # Delete a game >>> g . size # File count is automatically updated 2 Besides showing how descriptors can run computations, this example also reveals the purpose of the parameters to __get__() .

The self parameter is size , an instance of DirectorySize . The obj parameter is either g or s , an instance of Directory . It is the obj parameter that lets the __get__() method learn the target directory. The objtype parameter is the class Directory . Керовані атрибути ¶ A popular use for descriptors is managing access to instance data. The descriptor is assigned to a public attribute in the class dictionary while the actual data is stored as a private attribute in the instance dictionary.

The descriptor’s __get__() and __set__() methods are triggered when the public attribute is accessed. У наступному прикладі age є публічним атрибутом, а _age є приватним. Коли здійснюється доступ до публічного атрибута, дескриптор реєструє пошук або оновлення: import logging logging . basicConfig ( level = logging .

INFO ) class LoggedAgeAccess : def __get__ ( self , obj , objtype = None ): value = obj . _age logging . info ( 'Accessing %r giving %r ' , 'age' , value ) return value def __set__ ( self , obj , value ): logging . info ( 'Updating %r to %r ' , 'age' , value ) obj . _age = value class Person : age = LoggedAgeAccess () # Descriptor instance def __init__ ( self , name , age ): self . name = name # Regular instance attribute self . age = age # Calls __set__() def birthday ( self ): self . age += 1 # Calls both __get__() and __set__() Інтерактивний сеанс показує, що весь доступ до керованого атрибута age реєструється, але звичайний атрибут name не реєструється: >>> mary = Person ( 'Mary M' , 30 ) # The initial age update is logged INFO:root:Updating 'age' to 30 >>> dave = Person ( 'David D' , 40 ) INFO:root:Updating 'age' to 40 >>> vars ( mary ) # The actual data is in a private attribute {'name': 'Mary M', '_age': 30} >>> vars ( dave ) {'name': 'David D', '_age': 40} >>> mary . age # Access the data and log the lookup INFO:root:Accessing 'age' giving 30 30 >>> mary . birthday () # Updates are logged as well INFO:root:Accessing 'age' giving 30 INFO:root:Updating 'age' to 31 >>> dave . name # Regular attribute lookup isn't logged 'David D' >>> dave . age # Only the managed attribute is logged INFO:root:Accessing 'age' giving 40 40 Однією з основних проблем у цьому прикладі є те, що приватне ім’я _age закріплено в класі LoggedAgeAccess .

Це означає, що кожен екземпляр може мати лише один зареєстрований атрибут і що його ім’я не змінюється. У наступному прикладі ми вирішимо цю проблему. Індивідуальні імена ¶ Коли клас використовує дескриптори, він може інформувати кожен дескриптор про те, яке ім’я змінної було використано.

In this example, the Person class has two descriptor instances, name and age . When the Person class is defined, it makes a callback to __set_name__() in LoggedAccess so that the field names can be recorded, giving each descriptor its own public_name and private_name : import logging logging . basicConfig ( level = logging . INFO ) class Logged

The rest of this page is on the live site.