M
M
madwayz13372020-12-01 11:36:26
Python
madwayz1337, 2020-12-01 11:36:26

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)


How to extend the constructor of the CmdHandler class with the constructor of the Server class? Writing attributes manually is not an option, and inheritance is not.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vlad Grigoriev, 2020-12-01
@Vaindante

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

Z
Zanak, 2020-12-01
@Zanak

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 question

Ask a Question

731 491 924 answers to any question