Present class as dict or list

I have classes that are used to get data from one system, making some changes and then pushing them to another system. This is usually done by converting it to a dict or list after I have done all the necessary conversions.

So far, what I have done, I have made two methods called as_dict() and as_list() and used this when I need this view.

But I'm curious if there is a way to do dict(instance_of_my_class) or list(instance_of_my_class) .

I read magic methods and it seems that this is impossible.

And some simple code example to work with:

 class Cost(object): @property def a_metric(self): return self.raw_data.get('a_metric', 0) * 0.8 [..] # Repeat for various kinds of transformations def as_dict(self): return { 'a_metric': self.a_metric, [...] } 
+6
source share
1 answer

Do you mean something like this? If so, you should define a __iter__ method that gives key-value pairs:

 In [1]: class A(object): ...: def __init__(self): ...: self.pairs = ((1,2),(2,3)) ...: def __iter__(self): ...: return iter(self.pairs) ...: In [2]: a = A() In [3]: dict(a) Out[3]: {1: 2, 2: 3} 

It also seems like dict trying to call .keys / __getitem__ before __iter__ , so you can do list(instance) and dict(instance) to return something completely different.

 In [4]: class B(object): ...: def __init__(self): ...: self.d = {'key':'value'} ...: self.l = [1,2,3,4] ...: def keys(self): ...: return self.d.keys() ...: def __getitem__(self, item): ...: return self.d[item] ...: def __iter__(self): ...: return iter(self.l) ...: In [5]: b = B() In [6]: list(b) Out[6]: [1, 2, 3, 4] In [7]: dict(b) Out[7]: {'key': 'value'} 
+7
source

Source: https://habr.com/ru/post/943593/


All Articles