很抱歉关于课程的noob问题。我正在尝试将soap客户端分配给类函数内的变量,然后在其他类函数中访问该变量。我没有任何参数传递给setup_client()
函数。
在以下示例代码中,如何在self.client
之外访问setup_client()
,以便我可以在use_client()
中使用它,并且self.response
可以在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
1}}
(self, client=None)
我很快意识到,如果我在类定义中添加一个可选的客户端参数self.client = client
并包含duplicate symbol _response in:
/Users/myname/Library/Developer/Xcode/DerivedData/Garda_Station_Locator-dhfsoolpnjuqneegoeyzxismsykb/Build/Intermediates/Garda Station Locator.build/Debug-iphonesimulator/Garda Station Locator.build/Objects-normal/x86_64/Service.o
/Users/myname/Library/Developer/Xcode/DerivedData/Garda_Station_Locator-dhfsoolpnjuqneegoeyzxismsykb/Build/Intermediates/Garda Station Locator.build/Debug-iphonesimulator/Garda Station Locator.build/Objects-normal/x86_64/County.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
,那么在我的函数中尝试使用它时会出现None类型错误。
我意识到我对课程缺乏了解。我已经完成了一些关于课程的一般性阅读,但没有遇到任何描述我正在处理的具体例子。
答案 0 :(得分:2)
在两种情况下我都选择None,因为从逻辑上讲,在对象实例化时它们都不存在。它还允许您对逻辑进行一些完整性检查,例如
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
答案 1 :(得分:0)
首次创建实例时,可以不指定客户端,但在致电setup_client
之前,您需要务必致电use_client
。