pythonc++crtp

How to implement CRTP functionality in python?


I want to access a member (variable) of a derived class from a base class in python. In c++ I can use the CRTP design pattern for this. In c++, for example, I would do something like this:

#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;
            }
};

Usage:

int main(){

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

Any way I can implement this functionality in python?

What I want to do is to have a single base class that has a common set of functions that are based on derived class member variables. I want to avoid rewriting/repeating this common set of functions in all derived classes.


Solution

  • I'm not sure if it is what you are looking for, but as long as the subclass has an attribute, even though it's not defined in the baseclass it will be able to access it through the instance.

    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