问题:’id’是Python中错误的变量名

为什么id在Python中命名变量很不好?

Why is it bad to name a variable id in Python?


回答 0

id() 是基本的内置功能:

帮助id模块中的 内置功能__builtin__

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.)

通常,即使允许使用使用任何语言使关键字或内置函数都黯然失色的变量名也是一个坏主意。

id() is a fundamental built-in:

Help on built-in function id in module __builtin__:

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.)

In general, using variable names that eclipse a keyword or built-in function in any language is a bad idea, even if it is allowed.


回答 1

PEP 8-Python代码样式指南中,以下指南出现在“ 描述性:命名样式 ”部分:

  • single_trailing_underscore_ :按惯例用于避免与Python关键字冲突,例如

    Tkinter.Toplevel(master, class_='ClassName')

因此,为了回答这个问题,应用此准则的示例是:

id_ = 42

在变量名中包括结尾的下划线可以使意图很清楚(对于那些熟悉PEP 8指南的人)。

In PEP 8 – Style Guide for Python Code, the following guidance appears in the section Descriptive: Naming Styles :

  • single_trailing_underscore_ : used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

So, to answer the question, an example that applies this guideline is:

id_ = 42

Including the trailing underscore in the variable name makes the intent clear (to those familiar with the guidance in PEP 8).


回答 2

是一个内置函数,用于提供对象的标识(这也是CPython中的内存地址)。如果命名函数之一id,则必须说出builtins.id要获取的原始函数(或__builtins__.id在CPython中)。id全局重命名除了一个小脚本之外,其他任何地方都令人困惑。

但是,只要使用本地名称,将内置名称重用作为变量并没有什么坏处。Python具有许多内置函数,这些函数(1)具有通用名称,(2)无论如何都不会使用太多。可以将它们用作局部变量或作为对象的成员,因为从上下文可以明显看出您正在做什么:

例:

def numbered(filename):
    with open(filename) as file:
        for i, input in enumerate(file):
            print("%s:\t%s" % (i, input), end='')

一些带有诱人名称的内置函数:

  • id
  • file
  • listdict
  • map
  • allany
  • complexint
  • dir
  • input
  • slice
  • buffer
  • sum
  • minmax
  • object

is a built-in function that gives the identity of an object (which is also its memory address in CPython). If you name one of your functions id, you will have to say builtins.id to get the original (or __builtins__.id in CPython). Renaming id globally is confusing in anything but a small script.

However, reusing built-in names as variables isn’t all that bad as long as the use is local. Python has a lot of built-in functions that (1) have common names and (2) you will not use much anyway. Using these as local variables or as members of an object is OK because it’s obvious from context what you’re doing:

Example:

def numbered(filename):
    with open(filename) as file:
        for i, input in enumerate(file):
            print("%s:\t%s" % (i, input), end='')

Some built-ins with tempting names:

  • id
  • file
  • list, dict
  • map
  • all, any
  • complex, int
  • dir
  • input
  • slice
  • buffer
  • sum
  • min, max
  • object

回答 3

我可能会在这里说一些不受欢迎的东西:这id()是一个相当专业的内置函数,很少在业务逻辑中使用。因此,在紧密且编写良好的函数中将其用作变量名时,我看不出有任何问题,在这种情况下,显然id并不意味着内置函数。

I might say something unpopular here: id() is a rather specialized built-in function that is rarely used in business logic. Therefore I don’t see a problem in using it as a variable name in a tight and well-written function, where it’s clear that id doesn’t mean the built-in function.


回答 4

用内置函数命名任何变量都是不好的。原因之一是因为它会使不知道该名称被覆盖的读者感到困惑。

It’s bad to name any variable after a built in function. One of the reasons is because it can be confusing to a reader that doesn’t know the name is overridden.


回答 5

id是Python中的内置函数。分配一个值id将覆盖该功能。最好在中添加前缀,some_id或在中使用不同的大小写形式ID

内置函数采用单个参数,并为您传递的对象(在CPython中)的内存地址返回一个整数。

>>> id(1)
9787760
>>> x = 1
>>> id(x)
9787760

id is a built-in function in Python. Assigning a value to id will override the function. It is best to either add a prefix as in some_id or use it in a different capitalization as in ID.

The built in function takes a single argument and returns an integer for the memory address of the object that you passed (in CPython).

>>> id(1)
9787760
>>> x = 1
>>> id(x)
9787760

回答 6

因为它是内置函数的名称。

Because it’s the name of a builtin function.


回答 7

其他人提到它令人困惑,但是我想进一步解释一下为什么。这是一个基于真实故事的示例。基本上,我编写了一个带有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)

预期Yield:

Created Employee 'Taylor Swift' at 0x7efde30ae910

实际输出:

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

??我要在哪里叫int?这些都是内置的…

如果我将其命名为badge_idor id_,那么我就不会遇到这个问题。

Others have mentioned that it’s confusing, but I want to expand on why. Here’s an example, based on a true story. Basically, I wrote a class that takes an id parameter but then tried to use the builtin id later.

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)

Expected output:

Created Employee 'Taylor Swift' at 0x7efde30ae910

Actual output:

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

Huh? Where am I trying to call an int? Those are all builtins…

If I had named it badge_id or id_, I wouldn’t have had this problem.


回答 8

因为python是一种动态语言,所以给变量和函数起相同的名字通常不是一个好主意。id()是python中的函数,因此建议不要使用名为id的变量。请记住,这适用于您可能使用的所有函数…变量的名称不应与函数的名称相同。

Because python is a dynamic language, it’s not usually a good idea to give a variable and a function the same name. id() is a function in python, so it’s recommend not to use a variable named id. Bearing that in mind, that applies to all functions that you might use… a variable shouldn’t have the same name as a function.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。