【问题标题】:what "self" is doing in the selenium python code? [duplicate]selenium python代码中的“self”在做什么? [复制]
【发布时间】:2012-12-14 22:11:42
【问题描述】:

可能重复:
Python ‘self’ explained

我刚刚在selenium 文档的帮助下编写了如下代码,但对self 做了一些方法argument list 感到困惑?为什么我需要导入unittest 类?

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get("http://www.python.org")
        self.assertIn("Python", driver.title)
        elem = driver.find_element_by_name("q")
        elem.send_keys("selenium")
        elem.send_keys(Keys.RETURN)
        self.assertIn("Google", driver.title)

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

【问题讨论】:

  • 与任何其他类相同。如果您在不了解这些基础知识的情况下尝试使用像 Selenium 这样大的第三方库,那么您就走在了前面。

标签: python python-2.7


【解决方案1】:

self 用于在成员方法的情况下表示类的调用实例。这是必需的,以便类的成员方法作用于正确的对象。这与 Selenium 没有任何关系,而是该语言的一般特性。

类似于 C++ 中的this 参数

定义类时,在定义类的数据成员时使用self 参数,就像在您的类中所做的那样。

【讨论】:

  • unittest.main() 只是调用了unittest模块中定义的main函数
  • Selenium 在这里重用了unittest 框架,并且该框架根据需要创建TestCase 类的实例来运行测试。创建PythonOrgSearch 的实例在其他地方处理。
  • 创建类对象需要在python中做object = classname()。 Python 中的任何地方都不需要显式内存分配(据我所知)。
  • @AshRj:是的,Python 中的内存管理由 python 运行时负责。
  • @user1897085:你为什么不阅读python tutorial
猜你喜欢
  • 2022-12-08
  • 2011-10-12
  • 2018-03-14
  • 1970-01-01
  • 2019-04-21
  • 2010-10-12
相关资源
最近更新 更多