导入还是不导入类方法?

Import or not to import 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)

在 Python 3 中,无需导入 builtins 模块或其中的任何内容。当在当前范围内查找名称失败时,将查找 builtins 作为后备。

如果您需要维护代码完整性,请考虑在此之前明确检查 Python 版本。

import sys
if sys.version_info[0] == 2:
    from __builtin__ import classmethod

通常情况下,如果您的代码中也有一个与内置函数同名的变量并且还想访问内置名称,那么您只需要导入 builtins__builtin__。该模块的文档解释得很好:

builtins — Built-in objects

This module provides direct access to all ‘built-in’ identifiers of Python; for example, builtins.open is the full name for the built-in function open(). See Built-in Functions and Built-in Constants for documentation.

This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an open() function that wraps the built-in open(), this module can be used directly:

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.