How to implement CRTP functionality in python?

谁说胖子不能爱 提交于 2019-12-12 16:09:46

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/48055678/how-to-implement-crtp-functionality-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!