简体   繁体   中英

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.

Maybe you should take a step back and ask, why do we even use CRTP in C++. The reason for CRTP is that we might want to use a class polymorphically at compile-time or elide the virtual function call overhead.

Now Python does not have a “compile time” and because it is not statically typed all function calls are essentially virtual. Thus, you will obtain the same behaviour as with CRTP just with regular inheritance.

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

If, on the other hand you want CRTP to interact with the Python3 typing system, then you might want to checkout this question: Python 3 type hint for a factory method on a base class returning a child class instance

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM