Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how to create object or call method from class with kwargs

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()
like image 657
user2766739 Avatar asked Nov 06 '13 01:11

user2766739


People also ask

How do you pass Kwargs in a class Python?

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.

What is the correct way to use the Kwargs statement?

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.

How do you call a method object?

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.

What kind of object is Kwargs?

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 ** .


1 Answers

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.

like image 52
aIKid Avatar answered Sep 28 '22 12:09

aIKid