Generics/templates in python?

前端 未结 10 1473
深忆病人
深忆病人 2020-12-22 19:16

How does python handle generic/template type scenarios? Say I want to create an external file \"BinaryTree.py\" and have it handle binary trees, but for any data type.

10条回答
  •  南方客
    南方客 (楼主)
    2020-12-22 19:45

    Because Python is dynamically typed, the types of the objects don't matter in many cases. It's a better idea to accept anything.

    To demonstrate what I mean, this tree class will accept anything for its two branches:

    class BinaryTree:
        def __init__(self, left, right):
            self.left, self.right = left, right
    

    And it could be used like this:

    branch1 = BinaryTree(1,2)
    myitem = MyClass()
    branch2 = BinaryTree(myitem, None)
    tree = BinaryTree(branch1, branch2)
    

提交回复
热议问题