PYTHON

  minte9
REMEMBERS




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     github Class
Methods
        A B C D E F
🔔
1/2