gpt4 book ai didi

python - 在 Python 的类名中使用空格

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:56 25 4
gpt4 key购买 nike

在 python 中创建类的常规方法不允许在类名中使用空格。

>>> class Foo Bar(object):
SyntaxError: invalid syntax

但是,使用内置的 type()函数,我们可以创建一个名称中带有空格的类:

>>> C = type('Foo Bar', (object,),{})
>>> C
<class '__main__.Foo Bar'>

是否存在任何风险,或者使用带有空格的类名是否被认为是不好的做法?

最佳答案

没有风险,类 __name__ 是一个可写属性,它不用于任何特别重要的事情——只是无聊的东西,比如 repr 和帮助显示。

如果您尝试为其分配非字符串,则会出现自定义错误消息,这是 Python 开发人员有机会在此处限制为有效标识符的有力证据,他们有意选择不这样做:

>>> class A:
... pass
...
>>> A.__name__ = '123Class'
>>> A.__name__ = 123
TypeError: can only assign string to 123Class.__name__, not 'int'

这里是 Guido 回答了一个类似的问题——关于属性名称是否应该被限制为有效的标识符:

https://mail.python.org/pipermail/python-dev/2012-March/117441.html

I've spoken out on this particular question several times before; it is a feature that you can use any arbitrary string with getattr() and setattr(). However these functions should (and do!) reject non-strings.

同样的推理适用于类名(也可以作为任意字符串存储在模块命名空间中)。此功能的示例用例:确保在一系列类名和某些外部数据源之间存在一致的映射,即使外部数据与 Python 保留字或语法冲突也是如此。

关于python - 在 Python 的类名中使用空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51666361/

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