[Python] Intercepting and redirecting calls of a nested class structure in python

Discussão em 'Python' iniciado por Stack, Abril 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a very deeply nested class structure spanning multiple files and multiple levels of definitions. You can imagine this as a class describing some hardware system where each hardware component is represented by a class.

    class B():

    def __init__(self):
    self.attr_c = 0

    def setup_b(self):
    return "Setup of Class B might fail"

    class A():

    def __init__(self):
    self.attr_b = B()

    def setup_a(self):
    return "Setup of Class A might fail"

    def capture_a(self):
    return "Some real captured data"


    Class A is instantiated once at the beginning and after that, any of its nested members can be called.

    I'd like to create a virtual class (eg: class VirtualA) that replaces the instantiation of Class A at the beginning and allows me to use the same code as before without modification.

    The scope of VirtualA is to virtualize the hardware instruments at different nested levels and provide some virtual data.

    Requirements are:

    1. Some methods of any nested class should return a specific value (eg success or fail).
    2. Other methods (for example capture_a()) can be overwritten to return some virtualized data
    3. I don't want to replicate the whole structure of call and classes with a virtual counterpart (it would be too onerous). I just want to focus on methods that actually return data that I want to virtualize (eg see capture_a())
    4. Maintain debuggability

    example:

    # example of class VirtualA definition
    class VirtualA():

    def capture_a(self):
    return "Some virtual data"

    # TODO: add some minimal code (without replicating the whole nested class) to make the rest of the calls automatically pass


    # example of usage of class A
    a = A()
    a.setup_a()
    a.attr_b.setup_b()
    a.attr_b.attr_c = 1
    print(a.capture_a()) # -> "Some real captured data"

    # example of usage of class VirtualA
    a = VirtualA()
    a.setup_a()
    a.attr_b.setup_b()
    a.attr_b.attr_c = 1
    print(a.capture_a()) # -> "Some virtual data"

    Continue reading...

Compartilhe esta Página