Конструкция класса делегата приводит к ошибке рекурсииPython

Программы на Python
Anonymous
Конструкция класса делегата приводит к ошибке рекурсии

Сообщение Anonymous »


I'm building a framework and want to allow users to easily influence the construction of an object (e.g. singletons)

However no matter what I've tried I always get recursion. I wonder if there's a way to achieve this without altering create_instance. I'm sure I can probably achieve this by passing all the necessary stuff from the metaclass to the function, but the key is keeping it extremely simple for end users.

def create_instance(cls, *args, **kwargs): print("CUSTOM LOGIC TO CREATE INSTANCE") return cls(*args, **kwargs) class PersonMetaclass(type): def __call__(cls, *args, **kwargs): # Delegate creation elsewhere return create_instance(cls, *args, **kwargs) class Person(metaclass=PersonMetaclass): def __init__(self, *args, **kwargs): print("Person instance created") person = Person() Output:
CUSTOM LOGIC TO CREATE INSTANCE CUSTOM LOGIC TO CREATE INSTANCE CUSTOM LOGIC TO CREATE INSTANCE CUSTOM LOGIC TO CREATE INSTANCE .. E RecursionError: maximum recursion depth exceeded while calling a Python object !!! Recursion detected (same locals & position)

Источник: https://stackoverflow.com/questions/780 ... sion-error

Вернуться в «Python»