AutomaticStatic
AutomaticStatic

Reputation: 1739

Python: Class definition without arguments

Sorry for the noob question about classes. I'm trying to assign a soap client to a variable inside a class function and then access that variable in other class functions. I don't have any arguments to pass to the setup_client() function.

In the following example code, how do I make self.client accessible outside setup_client() so that I can use it in use_client(), and ditto making self.response available outside use_client()

class soap_call(self):
    def __init__(self):
        # What goes here?
        self.client = # what?
        self.response = # what?

    def setup_client(self):
        credentials = {'username': 'stuff', 'password': 'stuff'}
        url = 'stuff'
        t = HttpAuthenticated(**credentials)
        self.client = suds.client.Client(url, transport=t)

    def use_client(self):
        self.response = self.client.service.whatever
        print self.response

I quickly realized that if I add an optional client argument (self, client=None) to the class definition and include self.client = client, then I get a None type error when trying to use it in my functions.

I realize I just have a lack of understanding of classes. I've done some general reading up on classes but haven't come across any specific examples that describe what I'm dealing with.

Upvotes: 0

Views: 580

Answers (2)

Lim H.
Lim H.

Reputation: 10050

I'd go with None in both cases because logically speaking, none of them exists at the time of object instantiation. It also allows you to do some sanity checking of your logic, e.g.

class SoapCall(object):
    def __init__(self):
        self.client = None
        self.response = None

    def setup_client(self):
        credentials = {'username': 'stuff', 'password': 'stuff'}
        url = 'stuff'
        t = HttpAuthenticated(**credentials)
        if self.client is None:
            self.client = suds.client.Client(url, transport=t)

    def use_client(self):
        if self.client is None:
            self.client = self.setup_client()

        self.response = self.client.service.whatever
        print self.response

Upvotes: 2

chepner
chepner

Reputation: 531205

It's fine to leave the client unspecified when you first create the instance, but then you need to be sure to call setup_client before you call use_client.

Upvotes: 0

Related Questions