简体   繁体   中英

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. 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. 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.

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. 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."

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.

So you can make references like those in the second case work by adding lines to import the ui and expected_conditions modules explicitly:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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