如何在main def中调用类的函数。我试着调用self。“function”和“classname”。“function”但两者都不起作用......我想要的是在def main()中调用PiThread的def Temperature(self)。
类别:
class PiThread(threading.Thread):
Lock = threading.Lock()
# Lueftersteuerung bereitstellen
Motor1 = GPIO.PWM(17,500) # PWM mit Frequenz 500Hz
Motor2 = GPIO.PWM(27,500) # PWM mit Frequenz 500Hz
# 4 byte Sensordaten anfordern
Readout = bus.read_i2c_block_data(address,0,4)
CommandMode = (Readout[0] & 128) > 0
Stale = (Readout[0] & 64) > 0
# Sensor initialisieren
def SensorRequest(self):
void = bus.write_quick(address)
def Temperature(self):
RawTemperature = (self.Readout[2] * 256 + (self.Readout[3] & 252)) / 4
Temperature = round((165.0 / 16384) * RawTemperature - 40.0, 1)
return Temperature
def Humidity(self):
RawHumidity = (self.Readout[0] & 63) * 256 + self.Readout[1]
Humidity = round(100.0 * RawHumidity / 16384, 1)
return Humidity
主:
def main():
# Thread starten
controller = PiThread(SwitchTimes, GPIO);
controller.start()
while 1:
# Eingabefeld fuer Konsolenbefehle bereitstellen
command = raw_input("> ")
PiThread.Lock.acquire()
# Debug Informationen ausgeben
print "Luftfeuchte: ", PiThread.Humidity, "%"
print "Temperatur: ", PiThread.Temperature, "°C"
print "--------"
print "Luefter1 DC:", PiThread.x, "%"
print "Luefter2 DC:", PiThread.y, "%"
print "--------"
if command == "exit":
controller.stopIT();
break
PiThread.Lock.release()
controller.join()
if __name__ == '__main__':
main()
答案 0 :(得分:2)
温度和湿度是实例方法,因此您需要为特定实例调用它们,例如
print "Luftfeuchte: ", controller.Humidity(), "%"
print "Temperatur: ", controller.Temperature(), "°C"
或者使用@classmethod装饰器。
https://docs.python.org/2/tutorial/classes.html#instance-objects
https://docs.python.org/2/library/functions.html#classmethod