变量名为 `None`

-4 投票
5 回答
1809 浏览
提问于 2025-04-16 20:44

我需要一个变量,名字叫 None

class QAbstractPrintDialog(QDialog):
    None = int() # QAbstractPrintDialog.PrintDialogOption enum
    PrintToFile = int() # QAbstractPrintDialog.PrintDialogOption enum
    PrintSelection = int() # QAbstractPrintDialog.PrintDialogOption enum
    ...

但是:

语法错误:不能给 None 赋值

我想这个名字叫 None 是可以的。我以为这样做可以:

QAbstractPrintDialog.None = int() # QAbstractPrintDialog.PrintDialogOption enum

但结果并没有成功。有没有什么办法可以避免这个语法错误呢?像 setattr 这样的解决方案对我来说不管用,因为这段代码会被解析来提取类、函数、参数等等。

使用的是 Python 2.6 和 2.7

编辑:

我在帮一个人写伪 Python 模块,这些模块包含了 Qt 类的描述。QAbstractPrintDialog 是其中一个类,它有 enum QAbstractPrintDialog::PrintDialogOption(http://doc.trolltech.com/latest/qabstractprintdialog.html)。其中一个枚举值是 None。我可以通过 QAbstractPrintDialog.None 轻松引用这个 None 属性,但我不能给它赋值。int() 表示这个属性的类型。

可以查看这里: http://scummos.blogspot.com/2011/06/kdevelop-python-language-support-plugin.html

5 个回答

3

给它起个特别的名字,比如 __INSTEADOF_None,然后在解析之前,先把所有带有 '_INSTEADOF' 的部分去掉。

4

你不能这么做。None 是 Python 里一个内置的常量。

你想做的事情就像是:

class = struct

“给 None 赋值是非法的,会引发一个 SyntaxError 错误。” --文档说明

换个变量名吧:nilnonenothingzilchnot_a_sausageno_voteszero...

我同意你说的,这和其他内置常量有点不一致,比如:

>>> class Foo:
...     def __init__(self):
...             self.False = True
...             self.True = False
...             self.None = 'Something'
...
  File "<stdin>", line 5
SyntaxError: assignment to None

...但是...

>>> class Foo:
...     def __init__(self):
...             self.False = True
...             self.True = False
...
>>> f = Foo()
>>> f.True
False
>>> f.False
True
>>> f.None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute 'None'

...当然,这种命名和赋值方式只会带来麻烦!

10

在Python中,None是一个保留字,不能用作变量名。

根据Python的官方文档:

在2.4版本中,给None赋值是非法的,会引发一个语法错误。

撰写回答