我有一个函数,我想检查一下正在使用什么类型的请求,然后根据选择哪个函数运行另一个函数。
from tests.global_functions.util_helper import util_get_random_customer_individual
from tests.global_functions.util_helper import util_get_random_customer_company
import requests
def __init__(self):
request = requests.Requests()
if request == requests.Requests().data_add_customer_individual():
customer = util_get_random_customer_individual()
else:
customer = util_get_random_customer_company()
当我尝试运行它时,我得到了RuntimeError: maximum recursion depth exceeded while calling a Python object
如果我将import requests
更改为from requests import Requests
则会收到一条错误消息,指出它无法导入请求
我做错了什么?
我尝试执行以下操作:
request = requests.Requests
if request == requests.Requests.data_add_customer_individual():
customer = util_get_random_customer_individual()
else:
customer = util_get_random_customer_company()
并且我仍然得到递归深度超出错误。
以下是回溯:
File "C:Userse003048QAtrunkautomationseleniumsrcwebservicessystem_environmentcustomer.py", line 26, in __init__
if request == requests.Requests.data_add_customer_individual():
File "C:Userse003048QAtrunkautomationseleniumsrcwebservicessystem_environmentrequests.py", line 85, in data_add_customer_individual
my_request = request_data.RequestData()
RuntimeError: maximum recursion depth exceeded while calling a Python object
这个类被称为Requests
,它是否存在于一个名为requests
的模块中? 看起来很像你在类自己的构造函数中创建一个新对象。 回溯中显示的行将肯定地告诉您。
看起来您正在对data_add_customer_individual
进行的调用会导致创建当前类的新对象(因为您已经删除了class
语句,我不知道这叫什么)。这会导致递归对象创建,因为新对象也将调用 data_add_customer_individual
,这将创建另一个新对象等。
下面是一个做同样事情的小例子:
class Foo(object):
def __init__(self):
Bar()
def bar():
foo = Foo() # create a new Foo instance
print foo # this won't ever get reached, since the recursion happens above
通常,修复这种递归的一种方法是将Foo
对象的实例传递给bar
:
class Foo(object):
def __init__(self):
bar(self) # pass ourself as a reference!
def bar(foo): # bar now takes foo as a parameter, rather than creating it
print foo # this will work
因为我一遍又一遍地调用我自己的变量,所以它导致了最大递归错误。为了解决这个问题,我在Requests()
类中添加了一个名为 request_type = None
的变量,然后在我的 add_customer_individual
函数中,我声明了 request_type = 'individual' and the same for the
add_customer_company' 函数,只命名请求类型公司。
然后在我的客户课上,我做了以下工作:
request = Requests()
if request.request_type == 'individual':
customer = util_get_random_customer_individual()
elif request.request_type == 'company':
customer = util_get_random_customer_company()
else:
print 'What the hell should I do???? HELP!?!?!?!'
一旦我发现为什么我不能使用"从请求导入请求",这应该会立即工作