BOOKPYTHON Telegram 3370
В Python вы можете переопределить оператор квадратных скобок ([]), определив магический метод getitem. Примером может быть объект Cycle, который виртуально содержит бесконечное количество повторяющихся элементов:


class Cycle:
def __init__(self, lst):
self._lst = lst

def __getitem__(self, index):
return self._lst[index % len(self._lst)]

print(Cycle(['a', 'b', 'c'])[100]) # prints 'b'


Необычность здесь заключается в том, что оператор [] поддерживает уникальный синтаксис. Он может использоваться не только так — [2], но и так — [2:10], или [2:10:2], или [2::2], или даже [:]. Семантика — [start:stop:step], но вы можете применять её так, как вам нужно, для ваших собственных объектов.

Но что же получает getitem в качестве параметра index, если использовать этот синтаксис? Для этого существуют объекты slice.


In : class Inspector:
...: def __getitem__(self, index):
...: print(index)
...:
In : Inspector()[1]
1
In : Inspector()[1:2]
slice(1, 2, None)
In : Inspector()[1:2:3]
slice(1, 2, 3)
In : Inspector()[:]
slice(None, None, None)


Вы даже можете комбинировать синтаксис кортежей и срезов:


In : Inspector()[:, 0, :]
(slice(None, None, None), 0, slice(None, None, None))


Slice не делает ничего, кроме как просто хранит атрибуты start, stop и step.


In : s = slice(1, 2, 3)
In : s.start
Out: 1
In : s.stop
Out: 2
In : s.step
Out: 3


👉@BookPython
👍5



tgoop.com/BookPython/3370
Create:
Last Update:

В Python вы можете переопределить оператор квадратных скобок ([]), определив магический метод getitem. Примером может быть объект Cycle, который виртуально содержит бесконечное количество повторяющихся элементов:


class Cycle:
def __init__(self, lst):
self._lst = lst

def __getitem__(self, index):
return self._lst[index % len(self._lst)]

print(Cycle(['a', 'b', 'c'])[100]) # prints 'b'


Необычность здесь заключается в том, что оператор [] поддерживает уникальный синтаксис. Он может использоваться не только так — [2], но и так — [2:10], или [2:10:2], или [2::2], или даже [:]. Семантика — [start:stop:step], но вы можете применять её так, как вам нужно, для ваших собственных объектов.

Но что же получает getitem в качестве параметра index, если использовать этот синтаксис? Для этого существуют объекты slice.


In : class Inspector:
...: def __getitem__(self, index):
...: print(index)
...:
In : Inspector()[1]
1
In : Inspector()[1:2]
slice(1, 2, None)
In : Inspector()[1:2:3]
slice(1, 2, 3)
In : Inspector()[:]
slice(None, None, None)


Вы даже можете комбинировать синтаксис кортежей и срезов:


In : Inspector()[:, 0, :]
(slice(None, None, None), 0, slice(None, None, None))


Slice не делает ничего, кроме как просто хранит атрибуты start, stop и step.


In : s = slice(1, 2, 3)
In : s.start
Out: 1
In : s.stop
Out: 2
In : s.step
Out: 3


👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Share with your friend now:
tgoop.com/BookPython/3370

View MORE
Open in Telegram


Telegram News

Date: |

Co-founder of NFT renting protocol Rentable World emiliano.eth shared the group Tuesday morning on Twitter, calling out the "degenerate" community, or crypto obsessives that engage in high-risk trading. Commenting about the court's concerns about the spread of false information related to the elections, Minister Fachin noted Brazil is "facing circumstances that could put Brazil's democracy at risk." During the meeting, the information technology secretary at the TSE, Julio Valente, put forward a list of requests the court believes will disinformation. Members can post their voice notes of themselves screaming. Interestingly, the group doesn’t allow to post anything else which might lead to an instant ban. As of now, there are more than 330 members in the group. How to Create a Private or Public Channel on Telegram? Write your hashtags in the language of your target audience.
from us


Telegram Библиотека Python разработчика | Книги по питону
FROM American