You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python程序报错NameError: name 'bikeShop' is not defined原因排查

排查Python代码NameError错误:name 'bikeShop' is not defined

运行代码时抛出错误:

NameError: name 'bikeShop' is not defined

原代码:

class bikeShop:
    def __init__(self, stock):
        self.stock = stock

    def displayBike(self):
        print("Total Bikes", self.stock)

    def rentForBike(self, q):
        if q <= 0:
            print("Please Enter the value greater than zero")
        elif q > self.stock:
            print("Please Enter the less than the available stock")
        else:
            self.stock = self.stock - q
            print("Total price", q * 100)
            print("Total Bikes Available", self.stock)

    while True:
        obj = bikeShop(100)
        uc = int(input('''
    1. Display Stock
    2. Request a Bike For Rent (Price For One Bike is PKR.100/-)
    3. Exit      
                  '''))
        if uc == 1:
            obj.displayBike()
        elif uc == 2:
            n = int(input("Enter the Qty"))
            obj.rentForBike(n)
        else:
            break

错误原因

核心问题是缩进错误:你把while True循环直接写在了bikeShop类的内部(和类的方法同级缩进)。Python在解析类定义时会按顺序执行类内部代码,此时bikeShop类还未完成定义,就尝试创建该类的实例,自然找不到这个类名,从而抛出NameError。

修复方案

将while True循环的缩进退出来,放在类定义的外部,确保类完全定义后再执行实例创建和循环逻辑;同时优化实例创建位置,避免库存每次重置:

class bikeShop:
    def __init__(self, stock):
        self.stock = stock

    def displayBike(self):
        print("总自行车数量", self.stock)

    def rentForBike(self, q):
        if q <= 0:
            print("请输入大于0的数值")
        elif q > self.stock:
            print("请输入小于现有库存的数值")
        else:
            self.stock = self.stock - q
            print("总价格", q * 100)
            print("剩余可用自行车数量", self.stock)

# 先创建实例,再进入循环,避免库存每次重置
obj = bikeShop(100)
while True:
    uc = int(input('''
1. 显示库存
2. 租赁自行车(每辆价格100巴基斯坦卢比)
3. 退出      
              '''))
    if uc == 1:
        obj.displayBike()
    elif uc == 2:
        n = int(input("请输入租赁数量"))
        obj.rentForBike(n)
    else:
        break

内容的提问来源于stack exchange,提问作者Muhammad Irfan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 23:17:36