"谷歌端点无法自动更新上次请求的列表,即使我正在创建新的对象?"

2024-06-12 21:33:40 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是它第一次在列表中给出1个值,但从下一次开始,它将用新值返回以前的值。 #第一个请求答案:{“number”:[“1”]} #第二个请求答案:{“number”:[“1”,“1”]} #第三个请求答案:{“number”:[“1”,“1”,“1”]} #等等 #为什么新对象的列表会从以前的请求中获取值

import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote

class testInput(messages.Message):
    number = messages.IntegerField(1)

class testOutput(messages.Message):
    number = messages.IntegerField(1, repeated=True)

class counter:
    count = []  
    def add(self, number):
        self.count.append(number)

@endpoints.api(name='testClass', version='v1.0')
class testClass(remote.Service):


@endpoints.method(testInput, testOutput,
                  path='countNow', http_method='GET',
                  name='countNow')

def countNow(self, request):

    #creating a new object of counter class
    counterObj = counter() # NOTE: IT SHOULD A NEW INSTANCE AND ITS ALL OBJECT MUST BE NEW
                           # e.g count list must be empty

    #getting the new number from request
    requestNumber = int(request.number)

    #creating an object of output class
    output = testOutput()

    #adding the number in list
    counterObj.add(requestNumber) # NOTE: ADDING A NUMBER IN THE LIST
                                  #HENCE: LIST SHOULD CONTAIN ONLY ONE VALUE IN IT AND ITS LENGTH MUST BE: 1

    #storing the list in output
    output.number = counterObj.count

    #returning output
    return output #RETURNING THE LIST AND IT SHOULD RETURN ONLY SINGLE VALUE IN LIST



application = endpoints.api_server([testClass])

Tags: 答案fromimportselfnumberoutputcountcounter
1条回答
网友
1楼 · 发布于 2024-06-12 21:33:40

试试这个,构造函数__init__需要重新初始化

class counter:

    def __init__(self):
        self.count = []    # instance variable unique to each instance

    def add(self, number):
        self.count.append(number)

对你来说

class counter:
    count = []

这个变量count类变量将被所有实例共享

相关问题 更多 >