Answer the question
In order to leave comments, you need to log in
How do I extend the constructor of class X with the constructor of class N?
There is this code:
class CmdHandler:
def __init__(self, server):
self.somearg = 1
class Server(object):
def __init__(self):
self.event = None
self.obj = None
self.cmd = None
self.args = None
def handler(self):
CmdHandler(self)
Answer the question
In order to leave comments, you need to log in
The solution is straight forward, just roll all the arguments from server. But in a good way, it's better to do something explicitly through inheritance or properties or something else
class CmdHandler:
def __init__(self, server):
self.somearg = 1
self.__dict__.update({k: v for k, v in server.__dict__.items() if not k.startswith("_")})
class Server(object):
def __init__(self):
self.event = "None Server "
self.obj = None
self.cmd = None
self.args = None
def handler(self):
return CmdHandler(self)
h = Server().handler()
print(h.event)
>None Server
I didn’t really understand under what circumstances this case arose, so the questions are:
- extend class X to class N doesn’t it mean that N is a descendant of X?
- in the handler method, the parent creates an instance of the child, are you sure that this is correct?
Here, in my opinion, inheritance or encapsulation suggests itself.
If CmdHandler extends Server, then you can use inheritance by dragging common methods and data into the parent class.
If the classes are designed to interact, and their functionality does not overlap, then I would look towards passing the handler instance to the server constructor or a separate registration method in the instance.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question