1

When I read this document:

for k in self.fields

as the for loop description, it should be a list.

This mean an object instance's attribute fields. but in Python Base object there is no fields attribute, and you see the AsDictMixin is Inherited from object.

user7693832
  • 6,119
  • 19
  • 63
  • 114

2 Answers2

0

Mixins are usually designed to extend some functionalities of a class, not to be instantiated directly. And many times they are designed for a specific type of classes and written with knowing the implementation details of that type.

So in this case, presumably it exposes a as_dict method to convert the instance of the class where the mixin will be applied into a dict.

You need to check a class where the mixin is used as a superclass and you'll find self.fields there.

heemayl
  • 39,294
  • 7
  • 70
  • 76
0

Mixins are classes that are expected to be inherited by other classes that should have certain properties. It's something similar to an interface, but it provides partial concrete implementation rather than sheer abstract.

In [1]: class MyMixin:
   ...:     def get_evens(self):
   ...:         return [x for x in self.elements if x % 2 == 0]
   ...:

In [2]: class MyClass(MyMixin):
   ...:     def __init__(self, elements):
   ...:         self.elements = elements
   ...:

In [3]: mc = MyClass([1, 2, 3, 4, 5])

In [4]: mc.get_evens()
Out[4]: [2, 4]

There's a problem with a readability and code cleareness as you can see.

gonczor
  • 3,994
  • 1
  • 21
  • 46