python - Python 'self' 定义中的名称错误

标签 python linux

在 python 代码中获取名称错误:,如下所示。我是 Python 初学者。

from PyQt4 import QtGui, QtCore
import sys
import I2CGenericFrame
import os

class I2CApp(QtGui.QMainWindow, I2CGenericFrame.Ui_winI2CMain):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self)


    self.cmbBusListBox.addItem("Slect ..")

它给出以下错误。

Traceback (most recent call last):
  File "I2cMain.py", line 6, in <module>
    class I2CApp(QtGui.QMainWindow, I2CGenericFrame.Ui_winI2CMain):
  File "I2cMain.py", line 12, in I2CApp
    self.cmbBusListBox.addItem("Slect ..")
NameError: name 'self' is not defined

指导我,提前致谢。

最佳答案

self 是一个与方法中传递的任何其他参数一样的参数。它在方法之外的类主体中没有任何意义。

您可以通过修复缩进来解决此问题,以便在 __init__ 方法中引用它:

class I2CApp(QtGui.QMainWindow, I2CGenericFrame.Ui_winI2CMain):
    def __init__(self):
        super(I2CApp, self).__init__()
        self.setupUi(self)
        self.cmbBusListBox.addItem("Slect ..")

编辑:如评论中所示,您还应该显式调用该类的 super ,以避免无限递归的可能性。

关于python - Python 'self' 定义中的名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39876485/

相关文章:

Python 大函数多变量(重构)

linux - Pprof 和 golang - 如何解释结果?

c - 为什么这个 fork() 输出产生 8 而不是 5?

python - 如何获取 numpy 数组中给定项目的列索引和行索引(y 和 x)

python - 添加基于日期的类别列 - Pandas Dataframe

python - 使用距离过滤数据帧

linux - 将搁置的更改列表合并到分支中

linux - Ubuntu 20.04 - VPN 连接失败 - 找不到源连接

java - BufferedWriter 未写入文件

python - 为什么我不能使用unittest.mock.patch有效地模拟函数?