Problem 4: Pretty Printer (100pts)
Part 1
Your first task is to define pretty printer methods for Pet
, Cat
and NoisyCat
.
We start with implementing functions named to_str
for Pet
, Cat
, and NoisyCat
classes.
For Pet
, the output should be:
>>> kyubey = Pet('Kyubey', 'Incubator')
>>> kyubey.to_str()
'(Kyubey, Incubator)'
For Cat
and NoisyCat
, the output should be:
>>> vanilla = Cat('Vanilla', 'Minazuki Kashou')
>>> vanilla.to_str()
'(Vanilla, Minazuki Kashou, 9)'
>>> vanilla.lose_life()
>>> vanilla.to_str()
'(Vanilla, Minazuki Kashou, 8)'
Now, we could define a function pretty_print
, which accepts an object and print it prettily (i.e. with color).
To colorfully print something in terminal, this simplest way is to use ANSI escape code.
class Colors: HEADER = '\033[95m' OKBLUE = '\033[34m' OKCYAN = '\033[35m' OKGREEN = '\033[96m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' >>> print(f"{Colors.OKBLUE}Hello, World{Colors.ENDC}") Hello, World # this line should be blue >>> print(f"{Colors.OKCYAN}Hello, World{Colors.ENDC}") Hello, World # this line should be red >>> print(f"{Colors.UNDERLINE}Hello, World{Colors.ENDC}") Hello, World # this line should be underlined
Windows Console may not be able to display that. Use vscode console or windows terminal instead.
For real world program, you should use a library to display colorful output. E.g. termcolor
pretty_print
should print object with form type(to_str)
. The type
is the class name of the input object, the to_str
is the return value of object.to_str()
. For example:
>>> kyubey = Pet('Kyubey', 'Incubator')
>>> pretty_print(kyubey)
Pet(Kyubey, Incubator)
We ignore the ascii escape code in examples, you can check the real output in doctest
Note:
type
could be obtained by python builtintype(obj).__name__
. E.g.type(kyubey).__name__
isPet
- The
type
part of the printed str should be displayed with color defined byColors.OKBLUE
. For most device/terminal, this color should be blue. - The
to_str
part of the printed str should be displayed with color defined byColors.OKCYAN
. For most device/terminal, this color should be like red.
Part 2
Your second task is to inject the defined pretty_print
method to all Pet
, Cat
and NoisyCat
classes. For example:
>>> kyubey = Pet('Kyubey', 'Incubator')
>>> kyubey.pp() # the same result as `pretty_print`
Pet(Kyubey, Incubator)
To smoothly support such method call, edit the declaration of the Pet
class.
Hint1: You may not need to edit more than one line of code for this task.
Hint2: You should use the provided
PrintModule
class.
Test your code using python -i lab06.py
with:
>>> kyubey = Pet('Kyubey', 'Incubator')
>>> kyubey.pp()
Pet(Kyubey, Incubator)
>>> vanilla = Cat('Vanilla', 'Minazuki Kashou')
>>> vanilla.pp()
Cat(Vanilla, Minazuki Kashou, 9)
This is an ugly implementation of mixin. You can check this page for ruby style mixin, which is clear and elegant.