1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] python recursion error, calling classmethod of derived class in __new__ method

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    I have the following piece of code - simplified version of what I want to do. But it gives me a recursion error.

    class File:
    def __new__(cls, filename):
    extension = filename.split(".")[-1].lower()

    if extension == "csv":
    cls = CSVFile
    elif extension == "json":
    cls = JSONFile
    else:
    raise ValueError(f"Unsupported file extension: {extension}")

    # instance = super().__new__(cls) # this works
    instance = cls.create_instance(filename)
    return instance

    class CSVFile(File):
    def __init__(self, filename):
    self.filename = filename

    @classmethod
    def create_instance(cls, filename):
    print("CSVFile, create_instance")
    return cls(filename)

    class JSONFile(File):
    def __init__(self, filename):
    self.filename = filename

    @classmethod
    def create_instance(cls, filename):
    print("JSONFile, create_instance")
    return cls(filename)

    # Example usage
    file_instance = File("data.csv")
    print(f"File instance: {file_instance.filename}")


    Do you have idea how to make it work?

    Continue reading...

Compartilhe esta Página