如果您已经继承了 class,是否有必要导入它?

Is it necessary to import a class if you are already inheriting it?

在下面的代码中,小伙子导入了Qwidget class 并且还继承了Sample Window class中的Qwidget class 但是通过继承我们可以使用Qwidget的所有功能class。那么,他为什么要导入 Qwidget class?如果这是一个愚蠢的问题,我是新手 subject.Sorry。

# 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])

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)

A未导入时:

output:
Traceback (most recent call last):
   File "child.py", line 1, in <module>
     class B(A):
 NameError: name 'A' is not defined

正在导入 A:

from parent import A


class B(A):
    var_b = 5


    b = B()
    print(b.var_b)
    print(b.var_a)

    #output:
    5
    10

在第二种情况下,我们能够访问 class A(继承的)只是因为我们从 parent.py 文件中导入了 parent class A . 第一种情况给了我们未定义的错误,因为 class A 不在名称 space 中。

同样,如果 classes A 和 B 都存在于同一个文件中,我们将能够访问 B 的继承变量而不会出现未定义的错误,因为 A 已经在名称中space.