【问题标题】:Why is the result of `bool` True here? [duplicate]为什么 `bool` 的结果在这里为真? [复制]
【发布时间】:2021-09-19 11:12:12
【问题描述】:

这是我的代码:

class car():
    #defines a car model,speed,condition, and if you want to repair
    def __init__(self,model,speed):
        self.model = model
        self.speed = speed
        
    
    def roar(str = "vrooooooom"):
        print(str)
    
    def condition():
        user = bool(input('Is the car broken? True or False\n'))
        if user == True:
            print("Find local repair shop")
        else:
            print("No damage")

    def repair():
        wheels = ['O','O','O','O']
        if super().condition() == True:
            choice = input('Which one? 1-4\n')
            wheels[choice] = 'X'

当我调用 class.condition 并输入 False 时,即使我想要“无损坏”,我也会得到“查找本地维修店”。至于修复,我感觉我用super()错了。

【问题讨论】:

  • 欢迎来到 Stack Overflow。代码有很多问题,都是常见的问题。我将尝试链接所有重复项,从您实际询问的内容开始。
  • super 用于超类。您的班级没有(非平凡的)超类,因此工作 super 可能根本不应该出现在您的班级中。
  • "至于修复,我感觉我用super()错了。"我完全不明白你认为它应该是什么。但这是你应该通过阅读教程而不是试图在 Stack Overflow 上寻求帮助来解决的问题。这不是一个讨论论坛,所以问题应该主要是关于解决问题,而不是关于理解问题。

标签: python class methods super boolean-expression


【解决方案1】:

这不是它的工作原理。根据this post, Python 将任何 非空 字符串视为True。因此,当您输入False 时,它会变成一个非空 字符串,计算结果为True

相反,您应该这样做。

def condition():
    user = input('Is the car broken? True or False\n')
    if user == 'True':
        print("Find local repair shop")
    else:
        print("No damage")

【讨论】:

  • 任何时候你链接另一个 Stack Overflow 帖子,那里的答案已经足以回答 OP 的问题,这使得问题成为 duplicate 应该被标记为这样,而不是而不是自己回答。
  • 好的@KarlKnechtel,我会记住这一点
猜你喜欢
  • 2021-05-25
  • 1970-01-01
  • 2015-02-03
  • 2023-02-01
  • 2023-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多