- superclass vs subclass:
class DerivedClassName(BaseClassName):
class DerivedClassName(modname.BaseClassName):
e.g.class IntStack(Stack):
- built-in functions that work with inheritance:
a)Use isinstance() to check an instance’s type: isinstance(obj, int)
will be True only if obj.__class__ is int or some class
derived from int.b)Use issubclass() to check class inheritance: issubclass(bool, int) is True since bool is a subclass of int. However, issubclass(float, int) is False since float is not a subclass of int.
2. Exceptions:
e.g. class SpecialException(Exception):
pass
class ExtremeException(SpecialException):
pass
if __name__ == '__main__':
try:
#1/0
#raise SpecialException('I am a SpecialException')
#raise Exception('I am an Exception')
raise ExtremeException('I am an ExtremeException')
#1/0
except SpecialException as se:
print(se)
print('caught as SpecialException')
raise
except ExtremeException as ee:
print(ee)
print('caught as ExtremeException')
#raise
except Exception as e:
print(e)
print('caught as Exception')
Lab: Final question was solved by not shifting every positions after pop, but add 1 index to every elements, which saves operating time :)
19.5. Glossary
- exception
- An error that occurs at runtime.
- handle an exception
- To prevent an exception from causing our program to crash, by wrapping the block of code in a try ... except construct.
- raise
- To create a deliberate exception by using the raise statement.