python易错点 | AttributeError: 'xxxx' object has no attribute 'xxxx'

今天继续在学pyqt,跟着教程一个个敲代码的时候,以下代码出现错误:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class QPushButtonDemo(QDialog):
    def __init__(self):
        super(QPushButtonDemo,self).__init__()
        self.initUI()

	    def initUI(self):
	        self.setWindowTitle('QPushButton Demo')
	
	        layout=QVBoxLayout()
	
	        self.button1=QPushButton('第一个按钮')
	        self.button1.setText('First button')
	        self.button1.setCheckable(True)
	        self.button1.toggle()
	        self.button1.clicked.connect(lambda:self.whichButton(self.button1))
	        layout.addWidget(self.button1)
	
	        self.setLayout(layout)
	        def whichButton(self,btn):
	            print('被单击的按钮是<'+btn.text()+'>')

if __name__=='__main__':
    app=QApplication(sys.argv)
    main=QPushButtonDemo()
    main.show()
    sys.exit(app.exec_())

报错:

Traceback (most recent call last):
  File "E:/ICE的身家性命/iceplan0401/python课程/pylearning/pyqt/QPushButtonDemo.py", line 29, in <module>
    main=QPushButtonDemo()
  File "E:/ICE的身家性命/iceplan0401/python课程/pylearning/pyqt/QPushButtonDemo.py", line 9, in __init__
    self.initUI()
AttributeError: 'QPushButtonDemo' object has no attribute 'initUI'

我一个字一个地对教程,觉得怎么也灭有敲错啊,然后愕然发现,initUI这个函数被我多按了一个tab,按照python的规则就是归属于上一个函数了,难怪一直报错,这就属于对基础不熟练常犯的错误,写个博客记录一下。

python易错点 | AttributeError: 'xxxx' object has no attribute 'xxxx'_第1张图片

你可能感兴趣的:(错题集)