为什么这个Python代码不能在我的类函数下工作?

2024-06-14 21:39:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Jupyter笔记本上查过了。它应该在print函数中打印作业。它给出了错误:

NameError回溯(最近一次调用) 在里面 ---->;1级车: 2 3跑车=汽车() 4货车=汽车() 5卡车=汽车()

    <ipython-input-12-ff9e58e0b68d> in Car()
      1 class Car:
      2  
     ----> 3     sportscar = Car()
      4     van = Car()
      5     truck = Car()

    NameError: name 'Car' is not defined

怎样才能不把车定义在类下呢?你知道吗

class Car:

sportscar = Car()
van = Car()
truck = Car()
compact_car = Car()


sportscar.color = 'red'
sportscar.interior = 'leather'
sportscar.windows ='dark tint'
sportscar.top_speed ='150 mph'

van.color = 'gray'
van.interior = 'carpet'
van.windows = 'clear'
van.top_speed = '80 mph'

truck.color = 'midnight blue'
truck.interior = 'leather'
truck.windows = 'tint'
truck.top_speed = '100 mph'

compact_car.color ='white'
compact_car.interior = 'leather'
compact_car.windows = 'clear'
compact_car.top_speed = '90 mph'

print(sportscar.windows)
print(van.windows)
print(truck.color)
print(compact_car.color)

Tags: windowstopcarvan汽车colorspeedprint
1条回答
网友
1楼 · 发布于 2024-06-14 21:39:05

编辑Car类,使其如下所示:

# This class is where the problem was
class Car:
    def __init__(self): # The class just needs to be initialized
        pass 

Python找不到Car类的原因是它从未初始化过,所以就好像它从未被声明过一样。你知道吗

相关问题 更多 >