【问题标题】:Python Classes with methods [closed]带有方法的 Python 类 [关闭]
【发布时间】:2014-06-26 11:05:50
【问题描述】:

写一个Counter类的定义,包含:

  • 一个 int 类型的实例变量 counter,初始化为 0。
  • 一种名为 increment 的方法,将实例变量 counter 加一。它不接受参数或返回值。
  • 一种名为 get_value 的方法,它不接受任何参数。它返回实例变量 counter 的值。

这就是我目前所拥有的......

class Counter(object):
    def __init__(self, ct):
        self.counter = ct
    def increment(self):
        self.counter += 1
    def get_value(self):
        return self.counter

【问题讨论】:

  • 我没有看到“int 类型的实例变量计数器,初始化为 0”
  • 我的代码实验室说我在解决方案中的某些地方使用了不正确的数字。我不确定如何解决它....
  • @user3583742,你到底想用代码实现什么?
  • get_value 的目的是什么?您可以直接访问counter
  • Python class and methods 的可能重复项

标签: python class


【解决方案1】:

尝试在init方法中将实例变量counter初始化为0:

def __init__(self):
    self.counter = 0

其余代码没问题。

【讨论】:

  • 我已经输入了你在下面输入的内容,def __init__(self, ct): self.counter = ct.但它给了我同样的错误。
  • 用上面的代码替换你的 def __init__(self, ct)... 代码
  • 类 Counter(object): -----def __init__(self): ----------self.counter = 0 -----def increment(self) : ----------self.counter += 1 -----def get_value(self): ----------return self.counter
  • 那是我输入的,还没拿。我很困惑,不确定我的错误是什么。
  • 您是否尝试过创建 Counter 类的实例并在该实例上使用已定义的方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多