我想在类内为方法创建临时变量。并更新方法内部的变量。我想在循环内重用self.last_l
。但它不起作用。
这是我的代码:
import socket, mouseapi, mouseinput
from sys import stdout, exit
from decimal import Decimal
from math import fabs
from datetime import datetime
import time
import SocketServer
UDP_IP = "192.168.1.100"
UDP_PORT = 5005
class MyUDPHandler(SocketServer.BaseRequestHandler):
def setup(self):
self.before = 0
self.noise = 1.5
self.noise_f = 0.8
self.last_l = 0 # i want this temporary and updated on handle()
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
start = time.clock()
ndata = data.replace("[","")
ndata = data.replace("]","")
ndata = ndata.split(", ")
try:
ndata[1] = ("%.2f" % float(ndata[1]))
atas = ndata[1]
atas_bawah = int(int(float(atas)*100))
selisih = fabs(float(atas)-float(self.last_l)) # used here
if selisih > self.noise_f:
print "Selisih -> %.2f" % float(selisih)
print "Sensor -> %.2f" % float(atas)
self.last_l = atas # and updated here
atas_bawah = int(int(float(atas)*100))
end = time.clock()
print "Latency -> %.2gs" % (end-start)
if self.last_l == 0:
self.last_l = atas # or updated here
except keyboardInterrupt:
sys.exit(1)
if __name__ == "__main__":
HOST, PORT = UDP_IP, UDP_PORT
server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
server.serve_forever()
所以我希望打印的selish值小于或大于1。但它给我的不止一个。
^{pr2}$我试着用全球范围来做最后一个。还是不行。
当我试图把global last_l
放在last_l = 0
的任何地方,并将self.last_l
改为last_l
在handle
方法内。
处理程序无法看到对
self.last_l
的更新,因为在每个接受的请求上都会创建MyUDPHandler
的新实例。一、 处理程序的实例不被重用。在从
BaseRequestHandler
docstring:可能的解决方案:
last_l
值保留在全局范围内。在last_l
设置为self.server
(本例中是UDPServer
的实例)__call__(request, client_address, server)
方法的实例传递给SocketServer.UDPServer
和管理器last_l
状态。在请注意,这些解决方案都不是线程安全的(即,只能在单线程服务器上可靠地工作)。对于线程安全的解决方案,您必须用锁来保护对全局变量的写入。在
第一个解决方案的例子(最简单的一个)。为清晰起见,跳过无关行:
相关问题 更多 >
编程相关推荐