首页 > 解决方案 > 此代码中如何考虑对象的初始化?

问题描述

在这个类中没有称为“a”的属性,那么如何考虑 xa 呢?同样,什么是“xab”、“xabc”、“xabcd”、“xabcde”,它们是如何考虑的?在“xab”的情况下b是xa的属性,在“的情况下c是xab的属性吗? xabc”?简要说明!!!我完全糊涂了

class Node :
  def __init__(self, data = None, next = None) :
    self.data = data
    self.next = next
x = Node(50)
x.a = Node(40)
x.a.b = Node(30)
x.a.b.c = Node(20)
x.a.b.c.d = Node(10)
x.a.b.c.d.e = Node(5)
print(x.a.b.c.d.e.data)

标签: pythonpython-3.xclassobjectattributes

解决方案


我想类似于第一个变量的声明xx.a是该变量的隐式初始化。x在你初始化它之前不存在,x.a.

所以通过初始化x.a你首先需要x存在,这意味着你不能做类似的事情

class Node :
  def __init__(self, data = None, next = None) :
    self.data = data
    self.next = next
x = Node(50)
x.a = Node(40)
# Then try to create the chain until C without creating first b
x.a.b.c = Node(20)

如果您对其进行测试,它将指出

Traceback (most recent call last):
  File "<stdin>", in <module>
AttributeError: 'Node' object has no attribute 'b'

所以简而言之。我认为即使 Node 类没有属性,链只是为第一个变量创建子节点。

x 
|_ Node() -> self, data, next
|_ a _
     |_ Node () -> self, data, next
     |_ b _
          |_ Node () -> self, data, next
          |_ c _ 
               |_ ...

请注意,正如 quamrana 所述,onlya直接附加到x.


推荐阅读