python - 如果其他方法在类中的方法中不起作用

标签 python python-3.x class

代码在询问问题后在第 11 行终止。它确实运行 if 语句。程序也没有给出任何错误。

class Car():

    def __init__ (self, name):
        print (f"Hello and welcome {name}. You have won a Ferrari. Please enter the details below. \n")
        phone = input("Your phone number: ")
        address = input("Your home address: ")

    def sorry(self):
        print ("Hey! We are sorry, we do not ship beyond 2000 Miles.")

        response = input("Do you still want it? Yes or No? : ".upper())

        if response == "YES":
            print (f"Cool! {name}. Ride to us.")
        elif response == "NO":
            print (f"Oops! {name}. We are sorry to see you go. :(")
        else:
            "Have a Good day!"


Car1 = Car("Jack")
Car1.sorry()

最佳答案

  1. 确保将用户的输入保存到类的实例变量中,而不仅仅是方法的局部变量。

self.phone = input("您的电话号码:")

  • 通过调用 print 打印“祝你有美好的一天”响应。

  • 切勿在函数名称和左括号之间添加空格。

  • 所有变量名称均应小写,并可能包含下划线。

  • 访问 sorry() 方法内的实例变量 self.name,而不仅仅是一个 null 局部变量 name

  • print(f"酷!{self.name}。骑到我们这里来。")

  • 确保您对“Do you still Want it? Yes or No? :”的回答大写,而不是问题本身大写。
  • response = input("你还想要吗?是还是否?:").upper()

  • 请确保将用户名保存在构造函数中,以便稍后访问。
  • self.name = 名称

    尝试一下:

    class Car():
    
        def __init__ (self, name):
            print(f"Hello and welcome {name}. You have won a Ferrari. Please enter the details below. \n")
            self.name = name
            self.phone = input("Your phone number: ")
            self.address = input("Your home address: ")
    
        def sorry(self):
            print("Hey! We are sorry, we do not ship beyond 2000 Miles.")
    
            response = input("Do you still want it? Yes or No? : ").upper()
    
            if response == "YES":
                print(f"Cool! {self.name}. Ride to us.")
            elif response == "NO":
                print(f"Oops! {self.name}. We are sorry to see you go. :(")
            else:
                print("Have a Good day!")
    
    ca1 = Car("Jack")
    ca1.sorry()
    

    关于python - 如果其他方法在类中的方法中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55074572/

    相关文章:

    python - 如何在本地目录中有 avbin.dll(不是 C :\Windows\System) (for pyglet 1. 2.4)

    python - 停止 Pylons 中长时间运行的请求

    python - mysql查询在mysql-python中得到不同的结果

    python-3.x - 如何使用Python3解决Elasticsearch中的BUG INTEGER映射问题?

    python - 在字符串中添加 2 个小数,保留精度

    java - C++ "Object"类

    c++ - 是什么导致了我的错误?我正在尝试创建一个玩家类并将玩家名称存储为变量

    php - PHP OOP 中 $a=&$b 、 $a = $b 和 $a= clone $b 的区别

    python - 如何根据已经制作的 pandas 日期范围系列对特定日期进行分类(排序)?

    python - 如何在套接字之间正确中继 TCP 流量?