2014-10-27 88 views
-2

如何在主def中调用一个类的函数。我试图调用self。“function”和“classname”。“function”,但两者都不工作......我想要的是在def main()中调用PiThread的def Temperature(self)。如何在主def中调用一个类的函数?

类:

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

什么'PiThread.x和PiThread.y'? – 2014-10-27 16:44:51

回答

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

+0

不确定这里的类方法是否合适,因为在这些方法中使用了self。 – quamrana 2014-10-27 17:01:20

相关问题