python中基本的面向对象的实现

时间:2018-08-15 06:09:54

标签: python class oop object self

你好,我正在学习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()

1 个答案:

答案 0 :(得分:4)

  1. __init__方法外部的变量称为类变量,而方法内部的变量称为实例变量。这将回答您的问题:What is the difference between class and instance variables?
  2. 在python中,所有变量都是公共变量,因此不需要getter setter方法,除非您希望使用它们来保护变量值,或者想要在设置/获取变量之前处理/验证值。这里还有更多内容:What's the pythonic way to use getters and setters?
  3. 您的代码中存在设计缺陷。类Node代表一个节点。因此,如果必须使用此实现,我希望Node的所有方法都将在一个包含display的节点范围内。您实现了Node.display()以显示整个链接列表,因此您“不需要”一个LinkedList类。我认为最好添加一个LinkedList类和一个head变量来保存第一个节点,并添加一个display方法,就像您写的那样使其更加直观。