gpt4 book ai didi

python - 为什么这个Python代码在我的类函数下不起作用?

转载 作者:行者123 更新时间:2023-12-01 06:39:37 25 4
gpt4 key购买 nike

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

NameError Traceback(最近一次调用最后一次) 在 ----> 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

类下怎么可以不定义car呢?

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)

最佳答案

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

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

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

关于python - 为什么这个Python代码在我的类函数下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com