1

I am starting to learn Python from Java. I would like to write Python code similar to this line in Java:

public BinaryNode(T nodeData, BinaryNode<T> leftChild, BinaryNode<T> rightChild) {}

Here is what I have tried so far:

from typing import TypeVar

T = TypeVar('T')
class BinaryNode:

    def __init__(self, nodeData : T, leftChild : BinaryNode = None,
             rightChild : BinaryNode = None):
          self.nodeData = nodeData
          self.leftChild = leftChild
          self.rightChild = rightChild

How I should specify that the BinaryNodes passed to __init__ should have the same type parameter as the nodeData? Thanks for your help.

Timmy
  • 125
  • 1
  • 11
Hossmeister
  • 166
  • 1
  • 9
  • Why is this important to you? Surely, it's logically sound regardless of that specification. Any type-checker should be fine with it as well. – palivek Aug 07 '18 at 14:52

2 Answers2

1

Python uses Duck-Typing.

You don't need to specify type. It will resolve at running time.

Indeed, in Python you handle objects as they come. Therefore, if you handle your BinaryNodes as being of the same type of nodata and in some cases it isn't, then an error will occur and you should handle it if it is possible.

scharette
  • 9,437
  • 8
  • 33
  • 67
0

Okay, I think I figured out how to handle this:

class BinaryNode:

    def __init__(self, nodeData = None, leftChild = None,
                 rightChild = None):
        if leftChild is not None:
            try:
                assert leftChild.getData().type() is nodeData.type()
            except:
                print("Error: left child is not of proper type")
                exit()
        if rightChild is not None:
            try:
                assert rightChild.getData().type() is nodeData.type()
            except:
                print("Error: right child is not of proper type")
                exit()
        self.nodeData = nodeData
        self.leftChild = leftChild
        self.rightChild = rightChild

    def getData(self):
        return self.nodeData

I think this is the best way to do it, since the exceptions are handled at runtime.

Hossmeister
  • 166
  • 1
  • 9
  • A few things. You could just do an `if-else` instead of the `try-except`. Instead of printing and exiting you could just [raise](https://docs.python.org/3/tutorial/errors.html#raising-exceptions) an exception. `raise TypeError('Left child is not of proper type'`. – palivek Aug 07 '18 at 15:38
  • @palivek I don't think I could do an `if-else`, since `leftChild.getData()` might create an `AttributeError` if `leftChild` is not of type `BinaryNode`. Raising an exception is a good idea though. – Hossmeister Aug 07 '18 at 19:32
  • You could do `if isinstance(leftChild, BinaryNode): ...`. – palivek Aug 07 '18 at 19:37