【问题标题】:How do can I fix this issue about 'NoneType' error?如何解决有关“NoneType”错误的问题?
【发布时间】:2020-01-15 17:02:26
【问题描述】:
class lights(object):
    l1 = lights()
    l1.color = "blue"
    l1.quantity = 50
​
    l2 = lights()
    l2.color = "red"
    l2.quantity = 50    ​

AttributeError                            Traceback (most recent call last)
<ipython-input-11-1ae6b23b2a3d> in <module>
----> 1 class lights(object):
      2     l1 = lights()
      3     l1.color = "blue"
      4     l1.quantity = 50
      5 

在灯()中 1类灯(物体): 2 l1 = 灯() ----> 3 l1.color = "蓝色" 4 l1.数量 = 50 5

AttributeError: 'NoneType' object has no attribute 'color'

【问题讨论】:

  • lights 甚至不应该被定义。这显然重新定义了lights,它以前是一个在调用时返回None 的函数。
  • 显示更多代码可能会有所帮助。
  • 你想做什么?这段代码有一些问题,可能有助于理解您的主要目标以便更好地帮助...
  • 这能回答你的问题吗? How can I define a class in Python?

标签: python jupyter


【解决方案1】:

您似乎想要一个构造函数来定义灯光可能具有的属性:


class lights(object):
  def __init__(self):
    self.color = ""
    self.quantity = 0


l1 = lights()
l1.color = "blue"
l1.quantity = 50
l2 = lights()
l2.color = "red"
l2.quantity = 50

这将运行并创建两个lights 实例。

【讨论】:

  • class lights (object): 是完全正确的,尽管从 object 继承在 Python 3 中既没用也没有必要。问题是 l1 对象创建为类全局尝试实例化该类之前它已被定义。
  • @tripleee 谢谢,我不是 Python 爱好者,会正确回答
  • 好的,所以我还是有点困惑。所以我需要先定义 l1 然后继续这个? @tripleee
  • @Sean 你试图在lights 的声明中创建一个lights 实例,这将导致无限循环(如果它有效,但它没有,因为lights直到声明结束后才存在)Python是一种基于空格的语言,就像您缩进代码的方式一样,您试图在lights的声明中创建l1l2
  • 基本上,我所做的只是将创建l1l2 的代码移到lights 的声明之外,这样lights 在创建之前就存在,我添加了一个构造函数这样lights 就有colorquantity 成员。
猜你喜欢
  • 2018-08-22
  • 1970-01-01
  • 2020-12-10
  • 2023-01-16
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多