如何在python中实现CRTP功能?

时间:2018-01-02 04:43:25

标签: python c++ crtp

我想从python中的基类访问派生类的成员(变量)。在c++中,我可以使用CRTP设计模式。例如,在c ++中,我会做这样的事情:

#include <iostream>


template <class derived>
class Base {

    public:
        void get_value()
            {
            double value = static_cast<derived *> (this) -> myvalue_;
            std::cout<< "This is the derived value: " << value << std::endl;
        }

};
class derived:public Base<derived>{

    public:

        double myvalue_;

        derived(double &_myvalue)
            {
                myvalue_ = _myvalue;
            }
};

用法:

int main(){

    double some_value=5.0;
    derived myclass(some_value);
    myclass.get_value();
    // This prints on screen "This is the derived value: 5"
};

我可以在python中实现这个功能吗?

我想要做的是拥有一个单个基类,它具有一组基于派生类成员变量的通用函数。我想避免在所有派生类中重写/重复这个通用的函数集。

2 个答案:

答案 0 :(得分:3)

也许你应退后一步问,为什么我们甚至在C ++中使用CRTP。 CRTP的原因是我们可能希望在编译时以多态方式使用类,或者忽略虚函数调用开销。

现在Python没有“编译时间”,因为它不是静态类型,所有函数调用本质上都是虚拟的。因此,只需使用常规继承,您将获得与CRTP相同的行为。

class Base(object):
    def get_value(self):
        print("This is the derived value:", self.value)

class Derived(Base):
    def __init__(self, value):
        self.value = value

d = Derived(5)
d.get_value() # prints "This is the derived value: 5"

Live example

另一方面,如果您希望CRTP与Python3 typing系统进行交互,那么您可能想要查看此问题:Python 3 type hint for a factory method on a base class returning a child class instance

答案 1 :(得分:3)

我不确定它是否符合您的要求,但只要subclass具有属性,即使它未在baseclass中定义,将能够通过实例访问它。

class Base(object):
    def getValue(self):
        print(self.myvalue)



class Derived(Base):
    def __init__(self, myvalue):
        self.myvalue = myvalue



val = 3
derived = Derived(3)
derived.getValue()
#>3