Illusionist Illusionist - 28 days ago 9
Python Question

How do i instantiate this inherited class

Ok this should be trivial, but i am stuck- the code is existing and should be fine.

class Connect(object):
def __init__(self, database, user, password, host, port):
super(Connect, self).__init__()
self.database = database
self.user = user
self.password = password
self.host = host
self.port = port

class Process(Connect):
def __init__(self, **kwargs):
super(Process, self).__init__(**kwargs)


I can instantiate Connect easily

local_connection=Connect(database, user, password, host, port)


How do I instantiate Process?

If I do
Process(database, user, password, host, port
) -
Error is - TypeError: init() takes exactly 6 arguments (1 given)

If I do

Process(local_connection)


Error is - TypeError: init() takes exactly 1 argument (2 given)

If i try

Process()


Errorr is - TypeError: init() takes exactly 6 arguments (1 given)

Answer

You can fix this in two ways:

  1. create a Process's object along with argument's name as:

    >>> Process(database='database', user='user', password='password', host='host', port='port')
    <__main__.Process object at 0x7f4510150a10>
    
  2. OR, Use *args along with **kwargs in Process.__init__() as:

    class Process(Connect):
        def __init__(self, *args, **kwargs):
            super(Process, self).__init__(*args, **kwargs)
    

    and just pass param to __init__() without arguments as:

    >>> Process('database', 'user', 'password', 'host', 'port')
    <__main__.Process object at 0x7f4510150950>
    

Please also refer: What does ** (double star) and * (star) do for parameters? for knowing the difference between *args and **kwargs.