Generics/templates in python?

前端 未结 10 1503
深忆病人
深忆病人 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:51

    Python uses duck typing, so it doesn't need special syntax to handle multiple types.

    If you're from a C++ background, you'll remember that, as long as the operations used in the template function/class are defined on some type T (at the syntax level), you can use that type T in the template.

    So, basically, it works the same way:

    1. define a contract for the type of items you want to insert in the binary tree.
    2. document this contract (i.e. in the class documentation)
    3. implement the binary tree using only operations specified in the contract
    4. enjoy

    You'll note however, that unless you write explicit type checking (which is usually discouraged), you won't be able to enforce that a binary tree contains only elements of the chosen type.

提交回复
热议问题