How do I Use mixins in python?
class Database: def save_object(self): return 'id=34' def test(self): print("test from database") class Network: def save_object(self): return 'response 200' class Log: def log(self, message): print(message) def test(self): print("test from logger") class DatabaseStore(Database, Log): def save(self): self.test() self.log(self.save_object()) class NetworkStore(Network, Log): def save(self): self.test() self.log(self.save_object()) DatabaseStore().save() NetworkStore().save()
test from database id=34 test from logger response 200
Notice how the test() function is implemented in the Database class and Logger class but not in the Network class. Although both DatabaseStore and NetworkStore call the same functions, the result differs. The DatabaseStore mixes Database and Log which both have a test() function. The result is the return value from the Database. This is because of Method Resolution Order, or MRO. Database has the first match for test(). When test is called on the NetworkStore, the test result from the logger is returned because the Network does not have a test function at all. The calling of the save_object() function behaves like an inherited method.
Link to documentation or other source
13 Jun 2019
Author: Loek van den Ouweland
This example has been recommended 2 times.
Would you recommend this example to your colleagues?