gpt4 book ai didi

python - 导入还是不导入类方法?

转载 作者:太空狗 更新时间:2023-10-30 01:18:10 26 4
gpt4 key购买 nike

我希望这不是一个愚蠢的问题,但我发现了一些他们导入了 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 — 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

关于python - 导入还是不导入类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54290464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com