Python - inner class is not defined?

二次信任 提交于 2020-01-21 12:23:25

问题


I have to do an unrolled linked list for one of my classes. I'm new to python, but not to programming, and for some reason I cannot get around this little problem!

I have a class Node that is to be the node object used within the unrolled linked list. The unrolled linked list class performs all the operations on the Node class.

class UnrolledLinkedList(object):

    """ INNER NODE CLASS """
    class Node(object):
        def __init__(self):
            self.array = []
            self.next_node = None
    """ END NODE CLASS """

    def __init__(self, max_node_capacity=16):
        self.max_node_capacity = max_node_capacity
        self.head = Node()


    """ OTHER FUNCTIONS OF UNROLLEDLINKEDLIST CLASS """

The problem comes at the last line of the UnrolledLinkedList class' init function: "global name Node is not defined". I double checked my indentation and looked all over the internet for examples of something like this, but couldn't find any. Would someone mind explaining to me what's wrong?


回答1:


Methods do not include their class as a scope to be searched. If you want this to work then you will need to use either UnrolledLinkedList.Node or self.Node instead.




回答2:


The inner class Node is a member of the class UnrolledLinkedList and can only be accessed via self.

def __init__(self, max_node_capacity=16):
    self.max_node_capacity = max_node_capacity
    self.head = self.Node()



回答3:


Qualify Node() with self:

class UnrolledLinkedList(object):
    class Node(object):
        def __init__(self):
            self.array = []
            self.next_node = None

def __init__(self, max_node_capacity=16):
    self.max_node_capacity = max_node_capacity
    self.head = self.Node()

Python needs to qualify references to things. In this case, you could either say UnrolledLinkedList.Node() or self.Node().




回答4:


Use:

self.head = self.Node()

and it works.

A class does not create its own name space. Using self.Node(), Python first searches all attributes of the instances. Since it does not find the name Node there, it it searches the class UnrolledLinkedList for Node.

Alternatively, you can use the class name directly:

UnrolledLinkedList.Node()

You can achieve the same without nesting the class Node:

class Node(object):
    def __init__(self):
        self.array = []
        self.next_node = None

class UnrolledLinkedList(object):
    def __init__(self, max_node_capacity=16):
        self.max_node_capacity = max_node_capacity
        self.head = Node()


来源:https://stackoverflow.com/questions/34819921/python-inner-class-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!