Есть ли способ сделать "базовый класс шаблона" в Python? - PullRequest
0 голосов
/ 24 апреля 2018

Предположим, есть два класса Base1, Base2, которые унаследованы от общего базового класса Base.А также есть некоторая функция ff, которая работает с Base.

. В C ++ можно определить шаблонный класс Derived, который будет наследоваться от Base1 или от Base2, создавать объектывведите и передайте их ff:

// Given
struct Base1 : Base { };
struct Base2 : Base { };
void ff(const Base& base) { }

// you can do...
template < typename BB >
struct Derived : public BB { /* implement here what is common to both Derived1 and Derived2 */ };
struct Derived1 : public Derived<Base1> { /* implement here what is specific to Derived1 but not Derived2 */ };
struct Derived2 : public Derived<Base2> { /* implement here what is specific to Derived2 but not Derived1 */ };

// ... and live your life in peace with: 
Derived1 d1;
Derived2 d2;
ff(d1);
ff(d2);

Вопрос в том, как реализовать ту же архитектуру в Python3.6?

1 Ответ

0 голосов
/ 24 апреля 2018

Следующий код только для того, чтобы показать, что это возможно в Python, но IMHO, это не совсем Pythonic, потому что он просто имитирует шаблоны C ++.

>>> class Base:
    pass

>>> class Base1(Base):
    pass

>>> class Base2(Base):
    pass

>>> def templated(base):     # a Python decorator to mimic the C++ templating engine
    def outer(clazz):
        class Inner(base):
            _base = base      # a class attribute that will be tested later
        return Inner
    return outer

>>> class Derived:
    pass         # implement what is common to both Derived1 and Derived2

>>> @templated(Base1)
class Derived1:
    pass         # implement what is specific to Derived1

>>> Derived1._base        # to prove that it extends Derived<Base1> (C++ like syntax)
<class '__main__.Base1'>
>>> Derived1.__mro__      # base classes
(<class '__main__.templated.<locals>.outer.<locals>.Inner'>, <class '__main__.Base1'>,
<class '__main__.Base'>, <class 'object'>)
>>> 

Но на любом реальном примере, конечно,будь проще ...

...