
Christopher W. answered 06/08/17
Tutor
5.0
(37)
Very Knowledgable and Patient Computer Programming Tutor
# Start the class definition.
class Counter:
# Constructor (initialization method) definition.
def __init__(self, c=0, l=-1):
# Assign variables, passed into constructor, to
# instance variables:
self.counter = c
self.limit = l
# Note: 'self' reference is required for all methods.
def increment(self):
# BTW I'm just typing the Python equivalent to each
# line of your question...
if (self.counter < self.limit or self.limit == -1):
self.counter += 1
def decrement(self):
if (self.counter > 0): self.counter -= 1
def get_value(self):
return self.counter
## Notice that the __init__ method arguments default to 0 and
## -1, respectively, if they are not provided during class
## instantiation. Which effectively gives the counter a
## value of zero and sets an infinite limit, by default.
## (Note: the 'or' inside of the 'if' condition allows '-1'
## to represent 'no limit'.)
##
## You can run the following to check/test it out:
count = Counter()
count.counter
count.limit
count.increment()
count.get_value()
count.decrement()
count.get_value()
count2 = Counter(2, 4)
count2.counter
count2.limit
count2.increment()
count2.increment()
count2.increment()
count2.increment()
count2.get_value()
count2.decrement()
count2.decrement()
count2.decrement()
count2.decrement()
count2.decrement()
count2.get_value()
## See: https://docs.python.org/3.5/tutorial/classes.html
## and
## >>> help('class')
## >>> help('def')
##
## ~ veganaiZe ~