Write the definition of a class Counter containing:
class Counter:
counter = 0 #initialization of an instance variable called counter
# d a constructor that takes one int argument and assigns its value to counter
def __init__(self, a):
self.counter = a
# increment method that adds one to counter & does not take parameters or return a value
def increment(self):
self.counter+=1
# decrement method that subtracts one from counter & does not take parameters or return a value.
def decrement(self):
self.counter-=1
# method named get_value that returns the value of the instance variable ( counter)
def get_value(self):
print("counter value = " + str(self.counter))
# creating object of the class
# this will invoke parameterized constructor
x=10
print("Counter:"+str(x)+"\n")
obj = Counter(x)
# perform increment
obj.increment()
# display result
print("Increment operation result:\n")
obj.get_value()
# perform decrement
print("\nDecrement operation result:\n")
obj.decrement()
# display result
obj.get_value()
Comments
Leave a comment