如何修复我的IF语句,以便我不能从列表中删除和追加项目

时间:2019-06-20 02:21:41

标签: python

我目前正在编写一个简单的程序来为一家出租公司管理一个车场,到现在我还没有遇到任何实际问题。为了说明我的意思,我将发布代码,然后发布问题。

# class for Car_Yard
class CarYard():

    def __init__(self, listOfCars):
        self.availableCars = listOfCars

    def carYardCarsAvailable(self):
        print("Available Cars: ")
        for car in self.availableCars:
            print(car)

    def carYardRentCar(self, rentCar):
        if rentCar in self.availableCars:
            print("Congratulations on renting your new car, here\'s the keys")
            self.availableCars.remove(rentCar)
        else:
            print("We currently don't have that car in our yard")

    def carYardReturnCar(self, rentCarReturn):
        self.availableCars.append(rentCarReturn)
        print("You have returned the car. Thank You!")


# class for Buyer and his/hers actions
class Buyer():

    def buyerRentCar(self):
        print("Which car would you like to rent out?" )
        self.car = input()
        return self.car

    def buyerReturnCar(self):
        print("Which car would you like to return? ")
        self.car = input()
        return self.car


# create objects from class and pass a list of cars to the car yard
carYard = CarYard (['Mazda','Holden','Ford','Porsche','Honda','VW','Toyota','Kia'])
buyer = Buyer

# infinite loop
while True:
    print()
    print("Enter 1 to see our wide range of cars")
    print("Enter 2 to rent a car")
    print("Enter 3 to return a car")
    print("Enter 4 to leave the rental yard")
    print()

    userInput = int(input())

    if userInput is 1:
        carYard.carYardCarsAvailable()
    elif userInput is 2:
        rentCar = buyer.buyerReturnCar
        carYard.carYardRentCar(rentCar)
    elif userInput is 3:
        rentCarReturn = buyer.buyerReturnCar
        carYard.carYardReturnCar(rentCarReturn)
    elif userInput is 4:
        quit()

我遇到的问题是,当我运行代码并输入2时,它会自动跳到“我们目前院子里没有那辆车”这一行,而当我输入3时,它说“您已退还车。谢谢!”。

我试图弄清楚为什么我的代码没有被称为Buyer类来请求输入。关于我可能会缺少的任何建议吗?

1 个答案:

答案 0 :(得分:1)

您不应该这样使用isis运算符测试2个对象是否相同,这与测试它们的值是否相等是不同的。您真正想要的是一个相等测试(例如userInput == 1)。

无论如何,问题的根源在于您传递的是方法而不是这些方法返回的值。例如,这可能会更好:

buyer = Buyer()
...
elif userInput == 2:
    rentCar = buyer.buyerReturnCar()
    carYard.carYardRentCar(rentCar)

通过传递buyer.buyerRentCar就是将方法传递给carYardRentCar,自然地,它无法将该方法与汽车列表中的任何方法进行匹配。您想要的是传递carYardRentCar()返回的字符串。这将导致该方法被调用,要求用户进行输入,然后该方法的结果将被传递,这就是您想要的