python - 此代码中如何考虑对象的初始化?
问题描述
在这个类中没有称为“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)
解决方案
我想类似于第一个变量的声明x
,x.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
.
推荐阅读
- pine-script - Pinescript strategy.entry 多头/空头似乎被额外的 2 根蜡烛延迟
- reactjs - 如何将 React-Select 中的选定值转发到 react-hook-form
- r - mlrMBO 贝叶斯优化中 SVM 超参数调整的错误
- powershell - Powershell 全局变量用作参数的参数
- javascript - response.json 未定义 express.js
- arrays - 带数组的动态迭代。可能吗?如果是的话怎么办?
- python - /register/ 处的 ValueError 用户必须有一个电子邮件地址
- c# - 我的文本框不会在方法/按钮单击时填充?
- browser - 网站可以读取我的书签文件夹的内容吗?
- asterisk - 在 ubuntu 18.04 上安装星号