简体   繁体   中英

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM