如何重命名导入的模块类中存在的方法(函数)?你知道吗
总体思路:
#Current Generalized Code
from module import myImportedClass
X = myImportedClass.some_very_long_method_name_that_exists(*args).another_method(*args)
#Becomes Shorter Code
X = myImportedClass.SVLM(*args).AM(*args)
我有几个网页抓取脚本的工作,但想重写风格的代码长行到PEP8风格。我遇到的一个重复问题是详细的方法名(特别是来自seleniumwebdriver模块),这是一个导入的模块类。你知道吗
下面是我想做的事情的摘录。然而,在寻找之后,我不确定如何达到这个目的。我是否需要在Python脚本中编写某种本地类/函数,使别名的行为与原始方法名类似?你知道吗
#Current Example with Long Imported Class Method Names
from selenium import webdriver
d = webdriver.Firefox()
def load_job_cards(counter, job_key, job_type, filestem='newjobs'):
posts = d.find_elements_by_xpath("//div[@class=' row result clickcard']")
job_names = [j.find_element_by_css_selector("a[class='turnstileLink']").get_attribute('title') for j in posts]
#...more code...
#Would Like Imported Class Method to be Renamed, e.g.:
def load_job_cards(counter, job_key, job_type, filestem='newjobs'):
posts = d.find_elements_by_xpath("//div[@class=' row result clickcard']")
job_names = [j.fcss("a[class='turnstileLink']").ga('title') for j in posts]
#...more code...
以下脚本中记录了导入的WebDriver类方法,以供参考:
我不知道如何重命名,但只要一个小技巧就可以在这里使用函数指针, 将完整函数存储在变量中,然后调用新函数。你知道吗
我希望这对你有帮助
像这样的代码调用会变短
在@ashishkamble关于函数指针的建议的基础上,我为我的具体案例找到了一些解决方案。我仍然没有弄清楚如何重命名函数来继承原来的函数类方法的属性,例如
j.fcss("a[class='turnstileLink']").ga('title')
。你知道吗但是,用另一个函数解决原来的问题,我得到:
您可以从
myImportedClass
继承并定义新方法:那你就可以了
根据您的示例,请注意
find_element_by_css_selector
是WebDriver
的方法,而get_attribute
是WebElement
的方法,因此需要更新两个类。。。你知道吗但是!如果你真的需要让你的行更短,代码更可读,不要急着去做。新的类名和方法名可能会使使用/维护您的代码的人感到困惑。你知道吗
我建议您只需修改代码如下:
请注意,将元素定位器与执行代码分离是PageObject模式的基础,因此无论如何它都不是多余的
相关问题 更多 >
编程相关推荐