【发布时间】:2022-01-09 08:38:37
【问题描述】:
我是 Python 类的新手。我试图编写一个链表程序,我需要一个全局变量来计算节点数而不是函数。 所以,当我这样做时:
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
然后在链表类之外我无法访问这个 self.count(在我创建这个类的对象的部分等)我认为因为它是这个类的一个局部变量我得到了错误. 所以,我尝试了这个:
count = 0
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
global count
self.count=0
我在想,如果我把全局变量作为这个类的数据字段,那么我就不需要写了:
global count
在这个类下的每个函数中。 但是每当我访问计数时,它的值为零。 有人可以帮忙吗?
编辑:显示功能不需要这个计数,所以我可以看到我的列表被完美地创建了。我只想在类外使用 count 访问节点数,以便在调用插入或删除函数等之前检查位置有效性。 如果有帮助,我会将 sn-p 附加到它给我错误的位置:
pos = int(input("Enter the position : \n"))
if (pos>(count+1))or(pos<1):
print("Invalid Position")
【问题讨论】:
标签: python python-3.x class oop