【问题标题】:How come this Python code does not work under my class function?为什么这个 Python 代码在我的类函数下不起作用?
【发布时间】:2019-12-28 23:51:21
【问题描述】:

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

NameError Traceback(最近一次调用最后一次) 在 ----> 1 级车: 2 3 跑车 = Car() 4面包车=汽车() 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

类下怎么不能定义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 中创建那些Cars?我认为您想将该代码放在 Car 之外。
  • 你是什么意思?
  • 你不能有这样的空类块。尝试在 class Car: 下缩进 pass 由于空格在 Python 中很重要,如果问题正文中的缩进不正确,则很难知道您要做什么。
  • @MarkMeyer 这不是问题。这是一个粘贴错误。
  • @MichaelPaxinos 确保您的问题中的缩进与您的代码相匹配,我们只是在猜测。

标签: python class undefined


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2017-04-09
    • 2020-01-28
    • 2019-12-11
    • 2016-07-02
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    相关资源
    最近更新 更多