你好,我正在学习python,我有这个工作代码,但是在大多数面向对象的python示例中,我看到人们会使用额外的东西,但我不确定为什么我们需要这些。
我将尝试通过代码中的注释来解释我的问题。
class Node:
data = none
next = none
# Question1: Why do we have these variables outside of
# __init__ fucntion? what are their applications?
def __init__(self, val):
self.data = val
self.next = None
def display(self):
next = self
while next.next:
print next.data, "->",
next = next.next
print next.data
# Question2: Do we need getter setter functions to access
# the attributes above? I was able to remove a node with
# simple function and it worked well
def denode(node):
node.next = node.next.next
# Question 3: for many implementation samples of a linked
# list or something that uses Node, I see that example
# uses another class, but in the example below I was able
# to create a linked list without any trouble. why do we
# need a separate class to create a linked list?
#ex
node1 = Node(123)
node2 = Node(134)
node3 = Node(139)
node4 = Node(148)
node1.next=node2
node2.next= node3
node1.display()
denode(node1)
node1.display()
答案 0 :(得分:4)
__init__
方法外部的变量称为类变量,而方法内部的变量称为实例变量。这将回答您的问题:What is the difference between class and instance variables? Node
代表一个节点。因此,如果必须使用此实现,我希望Node
的所有方法都将在一个包含display
的节点范围内。您实现了Node.display()
以显示整个链接列表,因此您“不需要”一个LinkedList
类。我认为最好添加一个LinkedList
类和一个head
变量来保存第一个节点,并添加一个display
方法,就像您写的那样使其更加直观。