Utilizing mixins

Mixins is a concept that is present in every object-oriented language, and can be used to implement object classes that can be reused again and again in different places of the code. Projects such as Django web framework provide a lot of pre-built mixins, which can be used to achieve a certain set of functionality (for example, object manipulation, rendering of forms, and so on) in the custom classes we implement for our applications.

So, are mixins some special feature of the language? The answer to this is no, they are not some special feature, but rather are small classes that are not built to be turned into independent objects. Instead, they are built to provide some specified extra functionality to a class through the support of multiple inheritance.

Going back to our sample application, BugZot, we will need a way to return the data from multiple objects in JSON format. Now, we have two options; we can build the functionality of returning JSON data at the level of individual methods, or we can build a mixin that can be reused again and again in multiple classes:

Import json
class JSONMixin:
def return_json(self, data):
try:
json_data = json.dumps(data)
except TypeError:
print("Unable to parse the data into JSON")
return json_data

Now, let's imagine, if we wanted our bug class that we implemented in the example while trying to understand inheritance. All we needed to do was to just inherit JSONMixin in the Bug class:

class Bug(Request, JSONMixin):

And, by simply inheriting the class, we got the required functionality.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.163.238