+ 1
[solved] How to make mapping object?
SoloLearn's Python Core and Python Intermediate courses do not explain anything about custom mappings. So I have a question: how to make mapping object? If needed, this is my example code: https://code.sololearn.com/c5ac65WxNnk2/?ref=app
1 ответ
+ 2
to implement Mapping behavior, you should inherit from collections.abc.Mapping and implement __iter__ (keys), __getattr__ (values) and __len__ (length):
import collections.abc
class UnpackableObject(collections.abc.Mapping):
def __iter__ (self):
for i in range(1, 5): yield i
def __getitem__(self,prop):
return 'abcd'[prop-1]
def __len__(self):
return 4
print((*UnpackableObject(),))
print({**UnpackableObject()})