繁体   English   中英

需要确保我正确地解释了这个问题(我解决了这个问题,我需要一些支持来解除我的问题禁令)

[英]Need to make sure I interpreted the question correctly (I fixed the question I need some upvotes to lay off my question ban)

为名为 CounterType 的类型定义 class。 这种类型的 object 用于对事物进行计数,因此它记录的计数是非负整数。

一个。 私有数据成员:count。

湾。 包括一个mutator function,它将计数器设置为作为参数给出的计数。

c。 包括成员函数以将计数增加一并将计数减少一。

d。 包括一个返回当前计数值的成员 function 和一个输出计数的成员。

e. 包括将计数设置为 0 的默认构造函数。

F。 包括一个将计数设置为给定参数的参数构造函数。

确保没有成员 function 允许计数器的值变为负数。

将 class 定义嵌入到测试程序中。

output 示例将是:

a = CounterType(10)
a.display()
a.increase()
a.display()
a.setCounter(100)
a.display

将显示以下内容:

Counter: 10
Counter: 11
Counter: 100

我已经编写了代码,但我只想确保它遵循问题的要求,以及是否有更简单的方法来编写此代码。

class CounterType:
  def __init__(self, counter=0):
    self.counter = counter
  def increase(self):
    self.counter += 1
  def decrease(self):
    if self.counter == 0:
      print("Error, counter cannot be negative")
  else:
    self.counter -= 1
  def setCounter(self, x):
    if x < 0:
      print("Error, counter cannot be negative")
    else:
      self.counter = x
  def setCount0(self):
    self.counter = 0
  def display(self):
    print("Counter:", self.counter)
  def getCounter(self):
    return self.counter

这是一个家庭作业,所以如果你能提供一些提示会有所帮助

您忘记了“确保没有成员 function 允许计数器的值变为负数。”

天真的方法是在每个 function 中添加一个if条件。 更聪明的方法是添加检查setCounter function 并在所有其他功能中使用此 function。

class CounterType:

  def __init__(self, counter=0): # (e, f) counter = 0: default argument value so x = CounterType() works and has a counter of 0
    self.counter = 0  # (a)
    self.setCounter(counter)

  def increase(self): # (c)
    self.setCounter(self.counter + 1)

  def decrease(self): # (c)
    self.setCounter(self.counter - 1)

  def setCounter(self, x): # (b)
    if x < 0:
      print("Error, counter cannot be negative")
    else:
      self.counter = x

  def setCount0(self): # This is not needed
    self.counter = 0
  
  def display(self): # (d)
    print("Counter:", self.counter)

  def getCounter(self): # (d)
    return self.counter

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM