Python
/
Class
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 6
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tree S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Class Functional
Pure function, does not modify passed objects, and has no side effects. def increment_impure(x): x = x + 1 return int(x)
Pure Function
p278 A pure function does not modify any of the objects passed.
# Pure function ...
#
# does not modify any of the objects passed and ...
# has no side effects, like displaying a value or getting an input
class Hour:
"""Represents the day time
attributes: hour
"""
def increment_pure(t, d):
sum = Hour()
sum.hour = t.hour + d.hour
return sum
def increment_impure(t, d):
sum = Hour()
sum.hour = t.hour + int(d.hour) # Look Here
return sum
start = Hour()
start.hour = 9.0
duration = Hour()
duration.hour = 1.5
end = increment_pure(start, duration) # Correct
assert end.hour == 10.5
assert end.hour != 10
end = increment_impure(start, duration) # Wrong
assert end.hour != 10.5
assert end.hour == 10
# Side efects
end = increment_pure(start, duration) # Correct
def print_time(obj): # impure - side efects
print('%.2d' % obj.hour) # 2 digits
print_time(end) # 10
Modifiers
p280 Functions that modifiy the objects are called modifiers.
# Modifiers
#
# Functions that modifiy the objects are called modifiers.
#
# Pure functions are faster to develop and less error-prone, but ...
# modifiers are convenient at times and efficient.
class Time: pass
def increment(t, seconds): # modifier
t.seconds = t.seconds + seconds
def increment_pure(seconds): # pure
time = Time()
minutes, time.seconds = divmod(seconds, 60)
hour, time.minutes = divmod(minutes, 60)
time.hour = hour
return time
def print_time(t):
print('%.2d:%.2d:%.2d' % (t.hour, t.minutes, t.seconds))
t = Time()
t.hour = 9
t.minutes = 45
t.seconds = 0
increment(t, 20)
print_time(t)
# 10:45:20
t = increment_pure(160)
print_time(t)
# 00:02:40
➥ Questions