例如在__init__中声明的Python“AttributeError”

时间:2013-03-14 15:23:14

标签: python oop qtimer

我正在使用Python和Qt开发应用程序,我想澄清一些内容。拿这个代码示例:

import serial

from PySide.QtGui import QMainWindow
from PySide import QtCore, QtGui
from PySide.QtCore import QTimer
from ZumaUI import Ui_MainWindow

class MainWindow(QMainWindow, Ui_MainWindow):
    '''
    MainWindow: this is the class that manages all the functionality.
    '''
    def __init__(self, parent = None):
        '''
        Default Constructor. It can receive a top window as parent. 
        '''
        QMainWindow.__init__(self, parent)
        self.setupUi(self)

        self.serial = serial.Serial()
        self.serial.port = 'COM1'
        self.serial.baudrate = 19200
        self.serial.timeout = 0.5   #make sure that the alive event can be checked from time to time

        self.on_PortSettings()

        self.timer = QTimer(self)            
        self.timer.timeout.connect(self.OnRefresh)
        self.timer.start(150)

        self.on_PortSettings()

    def OnRefresh(self):
        pass

    def on_PortSettings(self):
        self.serial.close()
        self.timer.stop()

当我运行我的代码时,我得到了

"AttributeError: 'MainWindow' object has no attribute 'timer'"

但是我没有在类中全部调用的self.serial出现这种错误。这两个实例之间有什么区别?如何调用timer以便在整个课程中访问它?

2 个答案:

答案 0 :(得分:2)

在设置onPortSettings之前,您正在致电timer

    self.on_PortSettings() <-- here

    self.timer = QTimer(self)            

答案 1 :(得分:0)

这样做:

def __init__(self, parent = None):
    self.timer = None

...

def on_PortSettings(self):
    self.serial.close()
    if self.timer is not None:
        self.timer.stop()