【问题标题】:i need help on .append我需要关于 .append 的帮助
【发布时间】:2023-04-06 04:20:01
【问题描述】:

openLock 没有打印打开,它一直显示关闭。请问我的代码有什么问题。谢谢

class Padlock:
    def __init__(self, combination):
        self.code = combination
        self.code=[]

    def openLock(self,enteredCombination):
        self.enteredCombination= enteredCombination
        if self.code == self.enteredCombination:
            print("open")
        else:
            print("closed")

    def changeCombination(self, newCombination):
        if print == "open":
            print("type in new code")
            self.code.remove([0])
            self.code.append(newCombination)
        else:
            print("open lock first")
lock1=Padlock(1234)
lock1.openLock(1234)

【问题讨论】:

  • 这段代码怎么称呼?我看到的唯一想法是类定义。 Python 本身不会对类定义做任何事情。
  • lock1=挂锁(1234),lock1.openLock(1234),lock1.(4444)。谢谢
  • Edit 提供minimal reproducible example 的问题,实际上解释了问题
  • @thecodesalim: 但是你只调用不打印的__init__ 方法。此外,在您的__init__ 方法中,您只需再次覆盖self.code

标签: python class append


【解决方案1】:

您在构造函数中设置了self.code 2 次(2.time = [])。

我还添加了一个标志open 来保存锁的状态。 检查if print == "open" 没有像您预期的那样工作。

也不需要保存self.enteredCombination= enteredCombination,因为你只需要在方法中。

如果combinationint,则无需使用removeappend

class Padlock:
    def __init__(self, combination):
        self.code = combination
        self.open = True

    def openLock(self, enteredCombination):
        if self.code == enteredCombination:
            self.open = True
            print("open")
        else:
            self.open = False
            print("closed")

    def changeCombination(self, newCombination):
        if self.open:
            print("type in new code")
            self.code = newCombination
        else:
            print("open lock first")

code = "1234"
l = Padlock(code)
l.openLock(code)

newCode = "5678"
l.changeCombination(newCode)
l.openLock(code)
l.changeCombination(newCode)

l.openLock(newCode)

【讨论】:

  • @thecodesalim 请接受答案并暂时关闭问题。
猜你喜欢
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
  • 2014-09-25
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
  • 2017-08-05
  • 1970-01-01
相关资源
最近更新 更多