python - 导入还是不导入classmethod?
问题描述
我希望这不是一个愚蠢的问题,但我发现了一些他们导入classmethod
的代码和一些他们没有导入的代码,所以有区别吗?
我使用的是 python 3.6,但我认为最初的代码是用于 python 2.7(它使用from __builtin__ import
)
import unittest
from selenium import webdriver
from builtins import classmethod #original code was from __builtin__ import classmethod
class HomePageTest(unittest.TestCase):
@classmethod
def setUp(cls):
# create a new Firefox session
cls.driver = webdriver.Firefox()
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
# navigate to the application home page
cls.driver.get("http://demo-store.seleniumacademy.com/")
def test_search_field(self):
pass
#My tests without @classmethod
@classmethod
def tearDown(cls):
# close the browser window
cls.driver.quit()
if __name__ == '__main__':
unittest.main(verbosity=2)
解决方案
通常你只导入builtins
或者__builtin__
如果你的代码中还有一个与内置名称相同的变量,并且还想访问内置名称。该模块的文档很好地解释了它:
builtins - 内置对象
该模块提供对 Python 的所有“内置”标识符的直接访问;例如,
builtins.open
是内置函数的全名open()
。有关文档,请参阅内置函数和内置常量。大多数应用程序通常不会显式访问此模块,但在提供与内置值同名的对象的模块中很有用,但其中也需要该名称的内置。例如,在一个模块中,想要实现一个
open()
封装了内置函数的函数,open()
可以直接使用这个模块:import builtins def open(path): f = builtins.open(path, 'r') return UpperCaser(f) class UpperCaser: '''Wrapper around a file that converts output to upper-case.''' def __init__(self, f): self._f = f def read(self, count=-1): return self._f.read(count).upper()
但是,在您的情况下,文件中似乎没有classmethod
定义,因此您实际上并不需要from builtins import classmethod
.