class Accumulator():
def __init__(self, start=0):
self._sum = start
def __call__(self, x):
self._sum += x
print(f"I've now added {x} to my sum")
@property
def current_sum(self):
return self._sum
# initializing two instances with different starting values
adder_A = Accumulator(start=2)
adder_B = Accumulator(start=3)
adder_A(3)
I've now added 3 to my sum
adder_B(4)
I've now added 4 to my sum
adder_A(5)
I've now added 5 to my sum
adder_B(6)
I've now added 6 to my sum
adder_A.current_sum
10
adder_B.current_sum
13
class Count_to_10():
def __init__(self, start=0, step=1):
self.num = start
self.step = step
def __iter__(self):
return self
def __next__(self):
self.num += self.step
if self.num > 10:
print('I can only count to 10! :(')
raise(StopIteration)
return self.num
def set_step(self, step):
self.step = step
counter = Count_to_10(start=0, step=1)
next(counter)
1
next(counter)
2
counter.set_step(2)
for count in counter:
print(count)
4 6 8 10 I can only count to 10! :(
The cell below is for setting the style of this document. It's not part of the exercises.
# Apply css theme to notebook
from IPython.display import HTML
HTML('<style>{}</style>'.format(open('../css/cowi.css').read()))