I
I
Ivan2021-09-29 22:01:15
Python
Ivan, 2021-09-29 22:01:15

How to make indefinite inheritance in python?

There are N-number of classes:

class Validator:
class ApparelBeauty(Validator):
class ElectronicsSport(Validator):

and so on

It is necessary, depending on the condition, to inherit the resulting one of the classes.
class AutomaticWorker(active_class = check_active_category()):

And there is also a function that should substitute class names
def check_active_category():
  ...
  if config.getboolean('category', 'Apparel&Beauty') == True:
    return ApparelBeauty.__name__


I get
TypeError: AutomaticWorker.__init_subclass__() takes no keyword arguments

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-09-29
@FCKJesus

In general, the very need for such code is already a sign of serious problems.
But if you really need to ... In python, classes are objects of the first category. You can do everything with them as with other objects, for example, return them from functions. So there is no need to mess around with class_name.

L
LXSTVAYNE, 2021-09-30
@lxstvayne

There is such a solution through metaclasses :

import inspect

my_dog_age = 7


class SmallDog:
    pass


class MiddleDog:
    pass


class BigDog:
    pass


class DogMeta(type):
    def __new__(mcs, name, bases, namespace):

        dog = SmallDog
        if my_dog_age >= 10:
            dog = BigDog
        elif my_dog_age >= 5:
            dog = MiddleDog

        return super().__new__(mcs, name, (dog,), namespace)


class Dog(metaclass=DogMeta):
    pass


class MyDog(Dog):
    pass


print(inspect.getmro(MyDog))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question