【发布时间】:2018-01-02 04:43:24
【问题描述】:
我想从 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 中实现这个功能?
我想要做的是拥有一个单一基类,它具有一组基于派生类成员变量的通用函数。我想避免在所有派生类中重写/重复这组通用函数。
【问题讨论】: