I’ve been losing my mind over something that is possibly very plain.
A class is called which inherits a class dynamically from its keywords. Adding a helper class is likely the way to go. This is a nonworking illustration:
class Third:
def __init__(self, *args, **kwds):
self.string = 'XYZ'
class Agent(Third):
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
class Main:
def __init__(self, *args, **kwds):
if kwds.get('third_please'):
super(Agent, self).__init__(*args, **kwds) # Wrong usage.
print(self.string) # desired is 'XYZ'
Main(third_please=True)
This is based on an SO example and works when hard-coding the type call (Agent = type(‘Agent’, (Third,), {}). The problem is I want to supply ‘Third’ dynamically from another class call e.g. CallingClass(third_requested=True).
That is, I’d like for Main to inherit either Third or Fourth depending on keywords.
Adding additional classes is likely required but I’m unsure how to go about it.
class Fourth:
def __init__(self, *args, **kwds):
self.string = 'DEF'
class Third:
def __init__(self, *args, **kwds):
self.string = 'XYZ'
Agent = type('Agent', (Third,), {})
def __init__(self, *args, **kwds):
super(Agent, self).__init__(*args, **kwds)
Agent.__init__ = __init__
class Main(Agent):
def __init__(self, *args, **kwds):
if kwds.get('third_one_requested'):
super().__init__(*args, **kwds)
print(self.string)
Main(third_requested=True) # This is the main call