Answer to Question #173126 in Python for Mike

Question #173126

Write the definition of a class Counter containing:

  • An instance <u>variable</u> named counter of type int.
  • A constructor that takes one int argument and assigns its value to counter
  • A method named increment that adds one to counter. It does not take parameters or return a value.
  • A method named decrement that subtracts one from counter. It also does not take parameters or return a value.
  • A method named get_value that returns the value of the instance <u>variable</u> counter.
1
Expert's answer
2021-03-19T03:57:04-0400
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() 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS