I have the following parent class with kwargs init:
class A(object):
""" Parent class """
def __init__(self, **kwargs):
# connect parameters
self.host = kwargs.get('host', 'localhost')
self.user = kwargs.get('user', None)
self.password = kwargs.get('password', None)
def connect(self):
try:
self.ConnectWithCred( self.host,
self.port,
self.user,
self.password)
except pythoncom.com_error as error:
e = format_com_message("Failed to connect")
raise Error(e)
I want to create an object of 'class A' and call the 'connect' method. How do I go about? I tried the following and it wouldn't run (fyi - I'm a Python newbie):
sub_B = A(self.host = 'example.com', self.port = 22, self.user = 'root',
self.password = 'testing')
sub_B.connect()
Use the Python **kwargs parameter to allow the function to accept a variable number of keyword arguments. Inside the function, the kwargs argument is a dictionary that contains all keyword arguments as its name-value pairs. Precede double stars ( ** ) to a dictionary argument to pass it to **kwargs parameter.
The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks ( ** ) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.
Calling an object's method is similar to getting an object's variable. To call an object's method, simply append the method name to an object reference with an intervening '. ' (period), and provide any arguments to the method within enclosing parentheses.
kwargs is variable name used for keyword arguments, another variable name can be used. The important part is that it's a dictionary and it's unpacked with the double asterisk operator ** .
You're creating an instance of A
, not a subclass. Your problem is that your instantiation is a little incorrect, although close.
Remove self
from the keyword arguments:
sub_B = A(host = 'example.com', port = 22, user = 'root', password = 'testing')
This should work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With