Kev*_*tle 121
id() 是一个基本的内置:
有关
id模块 内置功能的帮助__builtin__:Run Code Online (Sandbox Code Playgroud)id(...) id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.)
通常,使用以任何语言遮蔽关键字或内置函数的变量名称都是一个坏主意,即使它是允许的.
Nat*_*ers 48
id是一个内置函数,它给出了一个对象的内存地址.如果您命名其中一个功能id,则必须说__builtins__.id要获取原始功能.id除了一个小脚本之外,全局重命名都会让人感到困惑.
但是,只要使用本地名称,重复使用内置名称作为变量并不是那么糟糕.Python有许多内置函数,(1)具有通用名称,(2)无论如何都不会使用太多.使用这些作为局部变量或作为对象的成员是可以的,因为从上下文中可以明显看出您正在做什么:
例:
def numbered(filename):
file = open(filename)
for i,input in enumerate(file):
print "%s:\t%s" % (i,input)
file.close()
Run Code Online (Sandbox Code Playgroud)
一些具有诱人名字的内置插件:
idfilelistmapall, anycomplexdirinputslicebufferDav*_*dRR 46
在PEP 8 - Python代码样式指南中,以下指南出现在描述:命名样式部分:
single_trailing_underscore_:用于避免与Python关键字冲突的约定,例如
Tkinter.Toplevel(master, class_='ClassName')
因此,要回答这个问题,应用此指南的示例是:
id_ = 42
Run Code Online (Sandbox Code Playgroud)
在变量名中包含尾随下划线使得意图清晰(对那些熟悉PEP 8中的指导的人).
Seb*_*tau 41
我可能会说一些不受欢迎的东西:id()是一个相当专业的内置函数,很少用于业务逻辑.因此,我没有看到在一个紧凑且编写良好的函数中将它用作变量名的问题,其中很明显id并不意味着内置函数.
wja*_*rea 10
其他人提到这很令人困惑,但我想详细说明原因。这是一个基于真实故事的例子。基本上,我编写了一个带有参数的类id,但后来尝试使用内置函数id。
class Employee:
def __init__(self, name, id):
"""Create employee, with their name and badge id."""
self.name = name
self.id = id
# ... lots more code, making you forget about the parameter names
print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))
tay = Employee('Taylor Swift', 1985)
Run Code Online (Sandbox Code Playgroud)
预期输出:
class Employee:
def __init__(self, name, id):
"""Create employee, with their name and badge id."""
self.name = name
self.id = id
# ... lots more code, making you forget about the parameter names
print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))
tay = Employee('Taylor Swift', 1985)
Run Code Online (Sandbox Code Playgroud)
实际输出:
Created Employee 'Taylor Swift' at 0x7efde30ae910
Run Code Online (Sandbox Code Playgroud)
啊?我想在哪里调用 int ?这些都是内置的...
如果我把它命名为badge_id或id_,我就不会遇到这个问题了。
更新:值得庆幸的是,这部分错误在 Python 3.11+ 中更加清晰:
Traceback (most recent call last):
File "company.py", line 9, in <module>
tay = Employee('Taylor Swift', 1985)
File "company.py", line 7, in __init__
print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))
TypeError: 'int' object is not callable
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40102 次 |
| 最近记录: |