【发布时间】:2018-04-24 11:10:43
【问题描述】:
假设有两个类Base1、Base2 继承自一个公共基类Base。还有一些函数 ff 可以与 Base 一起使用。
在 C++ 中,可以定义一个模板类 Derived,它将继承自 Base1 或 Base2,创建该类型的对象并将它们传递给 ff:
// Given
struct Base1 : Base { };
struct Base2 : Base { };
void ff(const Base& base) { }
// you can do...
template < typename BB >
struct Derived : public BB { /* implement here what is common to both Derived1 and Derived2 */ };
struct Derived1 : public Derived<Base1> { /* implement here what is specific to Derived1 but not Derived2 */ };
struct Derived2 : public Derived<Base2> { /* implement here what is specific to Derived2 but not Derived1 */ };
// ... and live your life in peace with:
Derived1 d1;
Derived2 d2;
ff(d1);
ff(d2);
问题是如何在 Python3.6 中实现相同的架构?
【问题讨论】:
-
我认为多重继承并不是你想的那样。
-
它目前的意思是我认为的意思。在尝试构建这样的架构时,它可能会被用于 Python 的技巧中。但是,是的,我没有提到这些技巧,因为它们并不能完全解决我的问题,也许我应该从标签中删除它。谢谢。
-
你最好询问你真正想要通过它实现的目标(在 python 中!)。尝试直接将代码从一种语言翻译成另一种语言通常会带来更多必要的困难,因为同一问题的解决方案可能完全不同
-
是的,这是可能的,而且它可能比 C++ 方式更简单,因为 Python 自然允许动态类型、鸭子类型和猴子补丁(这些名称只需要 google)。
标签: c++ python-3.x templates