[英]inherited class can not call base method in python using exec
I have following code as text file (for example: code.txt) 我有以下代码作为文本文件(例如: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_())
run this command, I got following error: 运行此命令,出现以下错误:
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
without 'super(B,self).a()', it is ok. 没有'super(B,self).a()'的话,还可以。 And if execute code in code.txt, it is also no problem
而且如果在code.txt中执行代码,也没有问题
Change code as following works: 更改代码,如下所示:
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_())
you can see only difference is exec(str) and exec(str,globals()) 您可以看到的唯一区别是exec(str)和exec(str,globals())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.