My setup: I am coding in python 3.7, with spyder4, on a windows10 machine.
Context
I am writing classes for a package. It is some kind of handler for classes defined in another package that I am importing.
Here is a simplified version of the situation:
# This I cannot modify, as they are in the package
class Letter_Class():
def __init__(self, name):
self.name = name
class A(Letter_Class):
def source(self):
print("from class A")
def funcA(self):
print("from class A")
class B(Letter_Class):
def source(self):
print("from class B")
def funcB(self):
print("from class B")
class C(Letter_Class):
def source(self):
print("from class C")
def funcC(self):
print("from class C")
# This I can modify
class Dynamic(Letter_Class):
def __new__(self, name, this_class): # -------- issue lies here? --------
obj = this_class(name)
return obj
def new_func(self):
print("function defined in dynamic class")
The classes Letter_Class
, A
, B
, C
have already been defined by someone else (in that 'other package' I am handling) and I cannot change them. I want to make a class, here called "Dynamic", who will inherit from a class given as an argument. It must still have the (many, many) methods that I wish to add such as new_func()
. I cannot know in advance which Letter_Class
child is used.
Classes A
, B
, C
have both polymorphic and specific methods, such as source()
and funcA()
. Because of that, I cannot make Dynamic
inherit from these classes. It would have been too easy.
Problem
If I execute the previous and the following code:
# user executes in main:
instance = Dynamic("test name", B)
print(instance.name)
instance.source()
instance.funcB()
instance.new_func()
I get:
test name
from class B
from class B
AttributeError: 'B' object has no attribute 'new_func'
The instance is created, source()
and funcB()
are executed without any problem.
Then, an attribute error is raised, because a Device
object was not truly created.
Could anyone explain to me what to put in the __new__()
constructor function to actually return an instance of the Device
class, with the proper inheritance from this_class
? I would be very grateful.
This discusion seems to address the issue, but in a different context and I cannot apply the suggested solution.