Библиотека Python разработчика. Книги по программированию на Python.
__getitem__ method:
In : class Iterable:
...: def __getitem__(self, i):
...: if i > 10:
...: raise IndexError
...: return i
...:
In : list(Iterable())
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The second way is to define __iter__ method that returns an iterator. An iterator is an object with a __next__ method that returns next value from the original iterable once called:
In : class Iterator:
...: def __init__(self):
...: self._i = 0
...:
...: def __next__(self):
...: i = self._i
...: if i > 10:
...: raise StopIteration
...: self._i += 1
...: return i
...:
...: class Iterable:
...: def __iter__(self):
...: return Iterator()
...:
...:
In : list(Iterable())
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Usually, an iterator also has an __iter__ method that just returns self: it allows iterator to be iterated too, that means that most of the iterators are also iterables.zip() мы можем все немного упростить.
Обратите внимание: функция zip() возвращает zip-объект, но с помощью приведения типов вы можете преобразовать его — например, с помощью list(), tuple() или dict().
Подписывайтесь на канал 👉@pythonofffifs. These are all and any.
any returns True if some of the values are true; all returns True if all of them are. all returns True for an empty iterable while any returns False in that case.
Both functions are usually useful while used together with list comprehensions:
package_broken = any(
part.is_broken() for part package.get_parts()
)
package_ok = all(
part.ok() for part package.get_parts()
)
any and all are usually interchangeable thanks to De Morgan's laws. Choose one that is easier to understand.obj.__class__ = AnyClass
Though it's probably a bad idea to use such tricks as part of your regular architecture, it can be extremely useful during debugging. Here is how you can track all attribute accesses of an object without modifying its original code:
class User:
def __init__(self, name):
self._name = name
def to_str(self):
return '<{}>'.format(self._name)
class LoggedUser(User):
def __getattribute__(self, attr):
print('`{}` accessed'.format(attr))
return super().__getattribute__(attr)
u = User('lol')
u.__class__ = LoggedUser
print(u.to_str())search, которая позволит вам найти подстроку
Если вам нужны сложные сопоставления, например, учет регистра — этот метод подойдет вам лучше всего. Но у него есть и недостатки: сложность и скорость работы. То есть, в простеньких задачах его лучше не использовать.
Подписывайтесь на канал 👉@pythonofffif 'port' not in config:
config['port'] = 80
port = config['port']
Setting default values to dictionaries can be done more elegant:
config = config.setdefault('port', 80)
setdefault sets the new value unless some value is already set. It also returns the new stored value whether it was changed or not:
In : config = {}
In : config.setdefault('port', 80)
Out: 80
In : config.setdefault('port', 443)
Out: 80@ operator since Python 3.5. It's intended to use for matrix multiplication. However, none of the standard objects support it; it was introduced specifically for the numpy module.
To make your objects support this operator, you should define one of the following methods: __matmul__, __rmatmul__ or __imatmul__.
You can learn more from PEP 465.