[英]Why can not import a subclass from main class in python
Hi in Selenium I want to import a child classes from library but I couldn't do it.您好 Selenium 我想从库中导入一个子类,但我做不到。 Below is totally fine;
下面完全没问题;
from Selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
But why I can not do such:但为什么我不能这样做:
from Selenium import webdriver
_WebDriverWait = webdriver.support.ui.WebDriverWait
_expected_conditions = webdriver.support.expected_conditions
The reason why I want to do this is in an editor, I am trying to supply a kind of sandbox environment and want user to be able to use all sub classes of pre-imported selenium.我想这样做的原因是在编辑器中,我试图提供一种沙盒环境,并希望用户能够使用预导入的 selenium 的所有子类。 How can I achieve this import?
我怎样才能实现这种导入?
The first one works and the second one doesn't because a path in the from
part of an import statement works differently from a path in an ordinary reference.第一个有效,第二个无效,因为 import 语句的
from
部分中的路径与普通引用中的路径不同。
In a from
clause, Python is willing to follow a path through a directory structure even if not all the names in the path have previously been imported.在
from
子句中,Python 愿意跟随路径通过目录结构,即使路径中的所有名称之前都没有被导入。 For an ordinary reference, it is not willing to do that.作为一个普通的参考,它不愿意这样做。
In the words of Real Python's article on the import system , "In general, submodules and subpackages aren't imported when you import a package."用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__
script for the webdriver
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__
脚本。
So you can make references like those in the second case work by adding lines to import the ui
and expected_conditions
modules explicitly:因此,您可以通过添加行来显式导入
ui
和expected_conditions
模块,从而使第二种情况中的引用起作用:
from selenium.webdriver.support import ui, expected_conditions
_WebDriverWait = ui.WebDriverWait
_expected_conditions = expected_conditions
This can make code like that in the second case work, but you may not consider it much of an improvement over the code in the first case.这可以使第二种情况下的代码工作,但您可能不会认为它对第一种情况下的代码有很大改进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.