继承类不能使用exec在python中调用base方法

时间:2016-08-10 19:57:23

标签: python inheritance exec base

我将以下代码作为文本文件(例如:code.txt)

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        str = '''
class A:
    def a(self):
        print('Hello')
        pass

class B(A):
    def a(self):
        super(B,self).a()
        print('World')
    pass    

b = B()
b.a()
'''    
        exec(str )        
if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

运行此命令,我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/xxx/xxx/w.py", line 28, in handleButton
    exec(str )        
  File "<string>", line 14, in <module>
  File "<string>", line 9, in a
NameError: name 'B' is not defined

没有&#39;超级(B,自我).a()&#39;,没关系。如果在code.txt中执行代码,那也没问题

1 个答案:

答案 0 :(得分:0)

按以下方式更改代码:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        str = '''
class A:
    def a(self):
        print('Hello')
        pass

class B(A):
    def a(self):
        super(B,self).a()
        print('World')
    pass    

b = B()
b.a()
'''    
        exec(str,globals() )        
if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

你只能看到差别是exec(str)和exec(str,globals())