繁体   English   中英

为什么不能从 python 中的主 class 导入子类

[英]Why can not import a subclass from main class in python

您好 Selenium 我想从库中导入一个子类,但我做不到。 下面完全没问题;

from Selenium import webdriver 
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions

但为什么我不能这样做:

from Selenium import webdriver
_WebDriverWait = webdriver.support.ui.WebDriverWait
_expected_conditions = webdriver.support.expected_conditions

我想这样做的原因是在编辑器中,我试图提供一种沙盒环境,并希望用户能够使用预导入的 selenium 的所有子类。 我怎样才能实现这种导入?

第一个有效,第二个无效,因为 import 语句的from部分中的路径与普通引用中的路径不同。

from子句中,Python 愿意跟随路径通过目录结构,即使路径中的所有名称之前都没有被导入。 作为一个普通的参考,它不愿意这样做。

Real Python 的关于导入系统的文章的话来说,“一般来说,当你导入 package 时,不会导入子模块和子包。”

Sometimes the __init.py__ script for a package will import some or all of the package's contents for you, so you don't have to worry about it, but in this case, Selenium doesn't do that for the support package in the __init.py__ webdriver package 的__init.py__脚本。

因此,您可以通过添加行来显式导入uiexpected_conditions模块,从而使第二种情况中的引用起作用:

from selenium.webdriver.support import ui, expected_conditions
_WebDriverWait = ui.WebDriverWait
_expected_conditions = expected_conditions

这可以使第二种情况下的代码工作,但您可能不会认为它对第一种情况下的代码有很大改进。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM