【发布时间】:2013-12-22 08:35:48
【问题描述】:
我想为类中的方法创建临时变量。并更新方法内部的变量。我想在循环内重用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()
所以我希望打印 selisih 值小于 1 或更多。但它给了我不止 1 个。
Selisih -> 6.53
Sensor -> 6.53
Latency -> 3.1e-05s
Selisih -> 6.70
Sensor -> 6.70
Latency -> 2.8e-05s
Selisih -> 6.97
Sensor -> 6.97
Latency -> 4.1e-05s
Selisih -> 7.15
Sensor -> 7.15
Latency -> 2.1e-05s
Selisih -> 7.14
Sensor -> 7.14
Latency -> 2.2e-05s
Selisih -> 7.14
Sensor -> 7.14
Latency -> 2.1e-05s
Selisih -> 7.05
Sensor -> 7.05
Latency -> 2.2e-05s
Selisih -> 7.02
Sensor -> 7.02
Latency -> 2.2e-05s
我试图让 last_l 具有全局范围。还是不行。
当我尝试将global last_l 后跟last_l = 0 并在handle 方法中将self.last_l 更改为last_l 时,我得到UnboundLocalError: local variable 'last_l' referenced before assignment。
【问题讨论】:
-
你能解释一下
it doesn't work到底是什么意思吗? -
题外话:我看到你是印度尼西亚人.. :) Jarang ketemu orang indo disini XD
-
你确定你的 try 块后面的语句运行没有错误吗?我首先猜想你在某个地方得到了 ValueError 并且一直只运行
pass行。请注意,简单地通过 ValueErrors 并不是一个好的例程,因为它们可能会为您提供有关错误所在位置的宝贵信息。 -
它不起作用,因为
self.last_l和我不能重复使用self.last_l值 -
@Gunslinger_ 尝试从
except ValueError子句打印一些内容,以检查它是否发生。
标签: python class variables methods udp