Issue
In the following code, the guy has imported the Qwidget class and also inherited the Qwidget class in the Sample Window class but by inheriting we can use all the functions of the Qwidget class. So, why did he imported the Qwidget class?I'm new to this subject.Sorry if it's a silly question.
# Import required modules
import sys, time
from PySide.QtGui import QApplication, QWidget, QIcon
class SampleWindow(QWidget):
# Constructor function
def __init__(self):
super(SampleWindow, self).__init__()
self.initGUI()
def initGUI(self):
self.setWindowTitle("Icon Sample")
self.setGeometry(300, 300, 200, 150)
# Function to set Icon
appIcon = QIcon('pyside_logo.png')
self.setWindowIcon(appIcon)
self.show()
if __name__ == '__main__':
# Exception Handling
try:
myApp = QApplication(sys.argv)
myWindow = SampleWindow()
myApp.exec_()
sys.exit(0)
except NameError:
print("Name Error:", sys.exc_info()[1])
except SystemExit:
print("Closing Window...")
except Exception:
print(sys.exc_info()[1])
Solution
Parent class(parent.py)
class A:
var_a = 10
Child Class(child.py)
class B(A):
var_b = 5
b = B()
print(b.var_b)
print(b.var_a)
When A is not imported:
output:
Traceback (most recent call last):
File "child.py", line 1, in <module>
class B(A):
NameError: name 'A' is not defined
Importing A:
from parent import A
class B(A):
var_b = 5
b = B()
print(b.var_b)
print(b.var_a)
#output:
5
10
In the second case, we were able to access class A (which was inherited) only because we imported the parent class A from the parent.py file. The first case gave us the undefined error as class A wasn't in the name space.
Along the same lines, if both classes A and B are present in the same file, we would be able to access inherited variables from B without that undefined error as A would already be in the namespace.
Answered By - Polaris000
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.