Python中的泛型/模板? [英] Generics/templates in python?

查看:154
本文介绍了Python中的泛型/模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python如何处理通用/模板类型的场景?假设我想创建一个外部文件"BinaryTree.py",并使其处理二进制树,但是对于任何数据类型.

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.

因此,我可以将自定义对象的类型传递给它,并具有该对象的二叉树.如何在python中完成?

So I could pass it the type of a custom object and have a binary tree of that object. How is this done in python?

推荐答案

Python使用鸭子输入,因此它不会不需要特殊的语法来处理多种类型.

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

如果您来自C ++背景,您会记住,只要在模板函数/类中使用的操作是在某种类型的T上定义的(在语法级别),就可以使用该类型模板中的T.

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. 为要在二叉树中插入的项目类型定义合同.
  2. 记录此合同(即在类文档中)
  3. 仅使用合同中指定的操作来实现二叉树
  4. 享受

但是,您会注意到,除非编写显式类型检查(通常不建议这样做),否则您将无法强制二叉树仅包含所选类型的元素.

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.

这篇关于Python中的泛型/模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆