为这个新手的问题道歉。我不确定我的措辞是否正确。
我在函数中有一个类,它列出了一组变量,我希望能够选择在最后一个函数调用时打印和返回哪些变量。但是,我显然不太了解对象来完成这一任务,因为当我试图尝试某件事情时,它会引发错误。
def gpscall(call):
#Write GPSinput
out = ''
ser.write(com.GPSstatus.encode())
time.sleep(1)
#Read output
while ser.inWaiting() > 0:
decoded = (ser.read(1).decode)
out += decoded()
strlen = len(str(out))
substr = out[0:strlen-9]
#GPS? information list
variables = substr.splitlines()
#Storing each output in a variable
class GPS:
PULSE_SAWTOOTH = [int(s) for s in variables[1] if s.isdigit()]
TRACKED_SATELLITES = [int(s) for s in variables[2] if s.isdigit()]
VISIBLE_SATELLITES = [int(s) for s in variables[3] if s.isdigit()]
LONGITUDE = variables[5]
longlen = len(LONGITUDE)
LONGDEG = LONGITUDE[0:longlen-7]
LONGMIN = LONGITUDE[longlen-7:]
LATITUDE = variables[6]
latlen = len(LATITUDE)
LATDEG = LATITUDE[0:latlen-7]
LATMIN = LATITUDE[latlen-7:]
HEIGHT = variables[7]
KNOTS = variables[8]
DEGREES = [9]
GPS_STATUS = variables[10]
TIMING_MODE = variables[17]
FIRMWARE_VERSION = variables[20]
print (call)
return (call)
if __name__ == "__main__":
#Call the functions
gpscall(gpscall.GPS.LATITUDE)这会引发错误,
函数“gpscall”没有“GPS”成员。
我不明白为什么它看不到这个类,我认为我使用的函数参数不正确。
任何帮助,我写得不好的代码,将不胜感激。
发布于 2020-02-09 05:48:03
也许是这样的,你的意图是?__init__ will initialize the object, and the self. will "save variables to the object."
class GPS:
def __init__(self):
#Write GPSinput
ser.write(com.GPSstatus.encode())
#Read output
out = ''
while ser.inWaiting() > 0:
decoded = (ser.read(1).decode)
out += decoded()
#GPS information list
substr = out[0:len(str(out))-9]
variables = substr.splitlines()
self.PULSE_SAWTOOTH = [int(s) for s in variables[1] if s.isdigit()]
self.TRACKED_SATELLITES = [int(s) for s in variables[2] if s.isdigit()]
self.VISIBLE_SATELLITES = [int(s) for s in variables[3] if s.isdigit()]
self.LONGITUDE = variables[5]
self.LONGDEG = LONGITUDE[0:len(LONGITUDE)-7]
self.LONGMIN = LONGITUDE[len(LONGITUDE)-7:]
self.LATITUDE = variables[6]
self.LATDEG = LATITUDE[0:len(LATITUDE)-7]
self.LATMIN = LATITUDE[len(LATITUDE)-7:]
self.HEIGHT = variables[7]
self.KNOTS = variables[8]
self.DEGREES = variables[9]
self.GPS_STATUS = variables[10]
self.TIMING_MODE = variables[17]
self.FIRMWARE_VERSION = variables[20]
gps = GPS()
print(gps.GPS_STATUS) 发布于 2020-02-09 05:45:27
该函数内部的Yor cls是完美的,没有什么问题。您只是试图以错误的方式调用函数和cls对象。
if __name__ == "__main__":
#Call the functions
gpscall(gpscall.GPS.LATITUDE) <---- ERROR HEREgpscall是一个函数,所以当您试图访问GPS.LATITUDE时,它将找不到任何对象。你得做任何一件事
gpscall(gpscall("").GPS.LATITUDE)但我认为最好的方法是在cls中编写func。您仍然可以访问cls的所有变量,并且不会造成太多麻烦。
PS:这是个好问题,不是一个菜鸟的问题。祝你好运(y)
https://stackoverflow.com/questions/60133777
复制相似问题