Python Forum

Full Version: Sort objects by protected properties.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
class AdjacencyList:
    def __init__(self, name=None, info=None):
        self._name = name  # head node name
        self._info = info  # head node info
        if not self.head().is_empty():
            self._tail = AdjacencyList()  # empty tail
            self._edges = Edge()  # empty list of edges
I am trying to sort my objects by name in lexicographical order.
I tried to apply the same principles as shown in this article.

My attempt to sort the objects is shown below:
 AdjacencyList.sort(key=lambda x: x._name, reverse=True)
However my IDE tells me two things.
1. Unresolved attribute reference ‘sort’ for class ‘AdjacenyList’
2. Access to a protected member _name of a class

So any better ideas on how I can do this? Think
Also the definition of the class "AdjacencyList" can't be changed. (But I can add more to it, i think)

If it matters, I think I want to sort the adjacency list in the same method that add new nodes to the list:
def add_node(self, name, info=None):
        if self.is_empty():
            self.__init__(name=name, info=info)
        else:
            node = self
            while not node._tail.is_empty():
                node = node.tail()
            new_node = AdjacencyList(name, info)
            node.cons(new_node)

        AdjacencyList.sort(key=lambda x: x._name, reverse=True)# my attempt to sort, that don't work 

        return self.head() 
It would be helpful if you would keep your code together as a unit and reference by line numbers in your dialogue.

Is add_node method of AdjacencyList?

If so, I'm not sure about creating an instance of class (new_node) within method looks dangerous at minimum,
but my head is yelling at me that it's not going to be OK.

At a minimum, your sort would have to be on new_node, and not on a class definition (AdjacencyList)
thus the warning:
Quote:Access to a protected member _name of a class