【发布时间】:2018-12-24 18:35:12
【问题描述】:
我正在尝试使用 OOP 和私有变量来实现一个链表。但是,当我调用 LinkedList 类的 display 方法时,我得到了 'str' object has no attribute 'get_data'。另外,我觉得add的方法也不对。
当我在add() 中打印self.__head 和self.__tail 时,代码永远不会进入else 部分并输出:
Sugar Sugar
Milk Milk
Tea Tea
Biscuit Biscuit
下面是我的代码:
class LinkedList:
def __init__(self):
self.__head=None
self.__tail=None
def get_head(self):
return self.__head
def get_tail(self):
return self.__tail
def add(self,data): # Skeptical about it
if self.__tail is None:
self.__head=Node(data).get_data()
self.__tail = self.__head
print(self.__head,self.__tail)
else:
b=Node(data)
self.__tail= b.get_data()
self.__head = self.__tail
b.set_next(self.__tail)
self.__tail = b.get_next()
print(self.__head,self.__tail)
def display(self): # Gives the error
temp = self.__head
msg = []
c = Node(temp)
while (temp is not None):
print(temp.get_data())
msg.append(str(temp.get_data()))
temp = temp.get_next()
msg = ''.join(msg)
print(msg)
class Node:
def __init__(self,data):
self.__data=data
self.__next=None
def get_data(self):
return self.__data
def set_data(self,data):
self.__data=data
def get_next(self):
return self.__next
def set_next(self,next_node):
self.__next=next_node
list1=LinkedList()
list1.add("Sugar")
#print(list1.get_head())
#print("Element added successfully")
list1.add("Milk")
list1.add("Tea")
list1.add("Biscuits")
list1.display()
【问题讨论】:
-
撇开不必要的双下划线名称修改,以及非常不符合 Python 标准的 getter 和 setter 使用,我想说这段代码中发生了很多奇怪的事情。
self.__head=Node(data).get_data()有什么意义???为什么不只是更直接和等效的self.__head = data?但这可能根本不是你想要的...... -
python 中没有私有属性(您的属性也是私有的)。删除 getter 和 setter,只使用
self.data和self.next。 -
因为数据是节点类的私有变量。
-
而__用于创建私有变量
-
正如 Daniel 所说,Python 中没有私有的东西。即使您使用
__尝试将事情设为私有,我也可以选择核选项并修复它,如果我真的想要访问。
标签: python oop linked-list