Python Forum
Sort objects by protected properties.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sort objects by protected properties.
#1
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() 
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I need help writing this code for string properties and methods hannah71605 4 3,125 Mar-22-2021, 12:36 PM
Last Post: menator01
  how to sort a list without .sort() function letmecode 3 3,448 Dec-28-2020, 11:21 PM
Last Post: perfringo
  [split] Manual Sort without Sort function fulir16 2 3,174 Jun-02-2019, 06:13 AM
Last Post: perfringo
  Manual Sort without Sort function dtweaponx 26 49,005 Jun-01-2019, 06:02 PM
Last Post: SheeppOSU
  Creating a script with a class have specific properties dvldgs05 13 5,834 Oct-15-2018, 08:54 PM
Last Post: dvldgs05
  newbie questions about objects properties... slowbullet 2 2,644 Aug-12-2018, 01:12 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020