This week we learned about stack superclass,
IntStack subclass and raising and catching exceptions. I have never learnt it
before.
I feel it was quite useful to learn how to
derive subclass from superclass. Since different objects may have something in
common. If we could inherit methods from other classes, we could save a lot of
work. This also makes the subclass easy to read. At first, I didn't understand
why we don't just copy and paste the existing code and modify it. Now I feel if
we could inherit from existing code, we could not only save space and time, but
also avoid making mistakes in modification.
It is also quite helpful to learn how to
write programs to handle exceptions. I felt frustrated for not fully
understanding how raising and catching exceptions works at first. Exceptions
are also classes. This identification helps me understand how exceptions work
in the code. Like some other classes, exceptions should be typically derived
from other Exception classes. We could use the raise statement to create a
specified exception to test our code. The really confusing part is the first
triggered matching except clause will be executed in raise statement.
A similar example from python official
website:
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except B:
print("B")
except C:
print("C")
except D:
print("D")
It would have printed B, B, B, instead of B, C, D.
No comments:
Post a Comment