Last active
August 9, 2018 17:10
-
-
Save Xorgon/b10d1eaff67a40a3e1dc9ef717e9c2cb to your computer and use it in GitHub Desktop.
How classes work in terms of pens
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Pen: | |
color = None | |
ink_level = None | |
active = True | |
def __init__(self, color="black", ink_level=1000): | |
self.color = color | |
self.ink_level = ink_level | |
def __str__(self): | |
return "A " + self.color + " pen." | |
def write_string(self, string): | |
if self.ink_level > len(string) and self.active: | |
print(string + " in " + self.color) | |
self.ink_level -= len(string) | |
elif self.ink_level < len(string): | |
raise (InkLevelError(self.ink_level, "You're out of ink!")) | |
else: | |
raise (ActiveError("Dude, not active!")) | |
def activate(self): | |
self.active = True | |
def deactivate(self): | |
self.active = False | |
class CappedPen(Pen): | |
cap_on = None | |
def __init__(self, cap_on=True, color="black", ink_level=1000): | |
super().__init__(color, ink_level) | |
self.active = not cap_on | |
self.cap_on = True | |
def put_cap_on(self): | |
print("I'm putting the cap on") | |
self.deactivate() | |
def take_cap_off(self): | |
print("I'm taking the cap off") | |
self.activate() | |
class ActiveError(RuntimeError): | |
""" This is just a dummy error so we can call it ActiveError. """ | |
def __init__(self, *args: object, **kwargs: object) -> None: | |
super().__init__(*args, **kwargs) | |
class InkLevelError(RuntimeError): | |
ink_level = None | |
def __init__(self, ink_level, *args: object, **kwargs: object) -> None: | |
super().__init__(*args, **kwargs) | |
self.ink_level = ink_level | |
# This bit is just a script that implements the pen stuff. | |
p = CappedPen(color="red") | |
p.take_cap_off() | |
try: | |
for i in range(1000000): | |
p.write_string("A poem") | |
except InkLevelError as err: | |
print("Dude, your ink level was " + str(err.ink_level)) | |
p.put_cap_on() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment