0

I am not sure how to return the object name, instead of its memory address. For instance:

class BSTNode:
    def __init__(self, data=None, left=None, right=None):
        self.data, self.left, self.right = data, left, right

    def search_bst(tree, key):
        return (tree if not tree or tree.data == key 
            else search_bst(tree.left, key)
            if key < tree.data else search_bst(tree.right, key))

I would like it to give me the Node name, such as "A", "B", "C" in the BST, instead of <__main__.BSTNode object at 0x7f64b9eedf28> etc.

If there is no easy way around it, I want to know if we can use the memory address to find the corresponding object name, along with other properties of the node.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
WQian
  • 13
  • 4
  • 2
    By "name" do you mean "what's in `self.data`"? In so, you want to write a `__repr__` method that returns something useful, like `return f'BSTNode({self.data!r})'`. Then, whenever you evaluate a `BSTNode` at the interactive prompt, you'll get something like `BSTNode('a')`. – abarnert Apr 03 '18 at 22:30
  • [Understanding `repr()` function in Python](https://stackoverflow.com/questions/7784148/understanding-repr-function-in-python) will probably be helpful here, although there's probably a question that this is a more direct duplicate of. (Oops, jonrshape already beat me to it…) – abarnert Apr 03 '18 at 22:32
  • Objects don't have "names" so it is unclear what you expect. By default, your class is inheriting `object.__repr__` and that is what is creating your string. – juanpa.arrivillaga Apr 04 '18 at 00:53

0 Answers0