简体   繁体   中英

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.

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, eg

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

初次创建实例时,可以不指定客户端,这是很好的选择,但是在调用setup_client之前,必须确保先调用use_client

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