Some of this week's topics are covered in Introduction to Computation:
chapter 7 "Exceptions and Assertions":
7.3 Assertions
chapter 8 "Classes and Object-Oriented Programming":
8.1 Abstract Data Types and Classes
8.2 Inheritance
8.3 Encapsulation and Information Hiding
And in Introducing Python:
Chapter 10. Oh oh: Objects and Classes
What Are Objects?
Simple Objects
Define a Class with class
Inheritance
Override a Method
Add a Method
Get Help from Your Parent with super()
In self Defense
Attribute Access
sName Mangling for Privacy
Here are some additional notes.
In Python, the assert
statement checks that a given
condition is true. If it is false, the program will fail with an
AssertionError. For example:
assert 0.0 <= prob <= 1.0
You may add an optional string which will be printed if the assertion fails:
assert 0.0 <= prob <= 1.0, 'probability must be between 0.0 and 1.0'
You can use assertions to verify conditions that should always be true unless there is a bug in the code. If such a condition is false, it is best to find out about it right away, rather than continuing to run and producing an incorrect result later, which may be difficult to debug.
You may also wish to use assertions to verify that arguments passed to a function are valid. For example:
# Compute the average value of numbers in list a def avg(a): assert len(a) > 0, 'list must be non-empty' return sum(a) / len(a)
In Python, you may use if
and else
inside an expression; this is called a conditional
expression.
For example, consider this code:
if x > 100: print('x is big') else: print('x is not so big')
We may rewrite it using a conditional expression:
print('x is ' + ('big' if x > 100 else 'not so big'))
As another example, here is a function that takes two integers and returns whichever has the greater magnitude (i.e. absolute value):
def greater(i, j): if abs(i) >= abs(j): return i else: return j
We can rewrite it using a conditional expression:
def greater(i, j): return i if abs(i) >= abs(j) else j
(If you already know C or another C-like language, you may notice this feature's resemblance to the ternary operator (? :) in those languages.)