[Python] How to structure class inheritance for shared state over multiple domains

Discussão em 'Python' iniciado por Stack, Junho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I need a class whose instances have shared state, but with methods that are the cross-products of operations and domains. For this example there are two operations (set and get) and two domains (french and spanish), and the application is to translate a string between languages.

    My actual application could have a dozen operations and a dozen domains, resulting in 144 possible things that could be done on a single instance. The answer to Python Borg Multiple Inheritance and Shared State says "just wrap the request for execution of an operation in an object that also includes the context", which in my case would result in 144 different OperationRequest classes, so that isn't a pattern I can use.

    Here is what I need to accomplish, supported by the shared context and domain operations classes:

    translate.py:

    from base import Base
    from french import French
    from spanish import Spanish

    b = Base() # Desired solution concept (doesn't run)
    b.setter(french('foo'))
    out = b.getter(spanish())

    # Runs individually but does not have shared state
    x = French()
    x.setter('bonjour le monde')
    print('text:', x.text)

    y = Spanish()
    out = y.getter()


    base.py:

    class Base:
    def __init__(self):
    self.text = None
    self.source = None


    french.py:

    from base import Base

    class French(Base):
    def setter(self, txt: str) -> None:
    self.text = {
    'foo': 'foo',
    'bonjour le monde': 'hello world'
    }[txt]

    def getter(self) -> str:
    out = {
    'foo': 'foo',
    'hello world': 'bonjour le monde'
    }[self.text]
    return out


    spanish.py:

    from base import Base

    class Spanish(Base):
    def setter(self, txt: str) -> None:
    self.text = {
    'foo': 'foo',
    'hola mundo': 'hello world'
    }[txt]

    def getter(self) -> str:
    out = {
    'foo': 'foo',
    'hello world': 'hola mundo'
    }[self.text]
    return out


    Current Approach: I use an inverted class hierarchy with Base statically inheriting methods from multiple parents:

    class Base(French, Spanish, German, Russian, ...):
    def __init__(self):
    self.text = None
    ...


    But this is not extensible. I need a mechanism, either single inheritance (preferable) or inverted multiple inheritance (yuck), that allows an application author to dynamically add operations on new "languages" without modifying existing library classes.

    Continue reading...

Compartilhe esta Página