为什么该Python代码在我的类函数下不起作用?

时间:2019-12-28 23:51:21

标签: python class undefined

我在Jupyter笔记本上运行了它。它应该在打印功能中打印作业。它给出了错误:

NameError跟踪(最近一次通话)          在         ----> 1级车:           2           3跑车= Car()           4厢型车= Car()           5辆卡车= Car()

    <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)

1 个答案:

答案 0 :(得分:0)

编辑您的Car类,如下所示:

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

Python找不到Car类的原因是它从未被初始化过,因此就好像它从未被声明过一样。