We now have changed and updated the design of our app.
Character Agile Sneaky
|_______________|______|
|
Thief
Tightly/Loosely Coupled Design
You want to create code that’s loosely coupled, so that it becomes easier to mix and match things around. Code that relies heavily on other code can make it very difficult to add in the functionality you want and need.
Example
Imagine you had code to send messages to users of your app.
- If your message sending code always used email for delivering those messages, it would be really hard to add in SMS or push notifications.
- If the code is more loosely coupled though and just expected there to be a send message method, you could swap out the backend much more easily.
characters.py
class Character:
def __init__(self, name="", **kwargs):
if not name:
raise ValueError("'name' is required")
self.name = name
for key, value in kwargs.items():
setattr(self, key, value)
attributes.py
import random
class Sneaky:
sneaky = True
def __init__(self, sneaky=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.sneaky = sneaky
def hide(self, light_level):
return self.sneaky and light_level < 10
class Agile:
agile = True
def __init__(self, agile=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.agile = agile
def evade(self):
return self.agile and random.randint(0, 1)
thieves.py
import random
from attributes import Agile, Sneaky
from characters import Character
class Thief(Agile, Sneaky, Character):
def pickpocket(self):
return self.sneaky and bool(random.randint(0, 1))
Method Resolution Order (MRO)
MRO controls the order that classes are searched through to find a particular method.
class Thief(Agile, Sneaky, Character)
This list of classes that your class extends, that order matters, because of how Python figures out which two similar super classes methods to call. This order is called a class’s method resolution order (MRO).
In this case, Character is the final class to be initialized.
play.py
from thieves import Thief
kenneth = Thief(name="Kenneth", sneaky=False)
print(kenneth.sneaky)
print(kenneth.agile)
print(kenneth.hide(8))