【问题标题】:'LinkedList' object has no attribute '__head' [duplicate]“LinkedList”对象没有属性“__head”[重复]
【发布时间】:2021-03-16 13:33:43
【问题描述】:

我是python链表的初学者。我正在尝试编写一个简单的程序来计算列表中的节点数,但我一直遇到这个错误。

我已经在 __init__ 函数中初始化了数据和 next 指针,但函数 count_nodes 似乎没有识别它。

我收到的错误:

```Runtime Exception
Traceback (most recent call last):
File "file.py", line 72, in <modules>
print(count_nodes(biscuit_list))
File "file.py", line 59, in count_nodes
top=biscuit_list.__head
AttributeError: 'LinkedList'object has no attribute '__head'```

```#lex_auth_012742478130135040816

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
    
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):
        new_node=Node(data)
        if(self.__head is None):
            self.__head=self.__tail=new_node
        else:
            self.__tail.set_next(new_node)
            self.__tail=new_node
    
    def display(self):
        temp=self.__head
        while(temp is not None):
            print(temp.get_data())
            temp=temp.get_next()
                                              
    #to print the elements of the DS object while debugging
    def __str__(self):
        temp=self.__head
        msg=[]
        while(temp is not None):
           msg.append(str(temp.get_data()))
           temp=temp.get_next()
        msg=" ".join(msg)
        msg="Linkedlist data(Head to Tail): "+ msg
        return msg

def count_nodes(biscuit_list):
    count=0
    top=biscuit_list.__head
    while(top.get_next):
        count+=1
        top=top.get_next

    return count

biscuit_list=LinkedList()
biscuit_list.add("Goodday")
biscuit_list.add("Bourbon")
biscuit_list.add("Hide&Seek")
biscuit_list.add("Nutrichoice")

print(count_nodes(biscuit_list))
                                 ```

【问题讨论】:

    标签: python list linked-list


    【解决方案1】:

    __head 是私有的,因为它以 __ 开头。检查这个答案Double underscore in python

    请改为使用get_head 方法来获取该值

    【讨论】:

    • 这是python3的“新”吗?我在 Python 中很少使用类(比如说:从不),但我想我记得在 Python2 中没有私有变量之类的东西,它只是用来告诉开发人员它是私有的。也许我也错了:)
    • 我在 python 2 中使用的类不多。所以我记不太清了。但是在python3中就是这种情况。我最近一直在使用私有变量。
    • 我刚刚测试过。看起来python 2也是如此。但据说它并不是真正的私有,因为它实际上是可以访问的,正如我附加的链接中所解释的那样。因此,在您的情况下,您应该能够通过biscuit_list._LinkedList__head 访问__head。但推荐的方法是使用 getter 方法。使用命令dir(biscuit_list) 可以了解哪些是可访问变量和方法的一种方法
    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2021-05-07
    • 2016-09-20
    • 2013-06-25
    • 2018-09-12
    • 2019-11-09
    相关资源
    最近更新 更多