不是有效的python标识符的属性 [英] Attributes which aren't valid python identifiers

查看:141
本文介绍了不是有效的python标识符的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

常用的属性访问方法要求属性名称为有效的python标识符.

The usual method of attribute access requires attribute names to be valid python identifiers.

但是属性不必是有效的python标识符:

But attributes don't have to be valid python identifiers:

>>> class Thing:
...     def __init__(self):
...         setattr(self, '0potato', 123)
...         
>>> t = Thing()
>>> Thing.__getattribute__(t, '0potato')
123
>>> getattr(t, '0potato')
123

当然,t.0potato仍然是SyntaxError,但是该属性仍然存在:

Of course, t.0potato remains a SyntaxError, but the attribute is there nonetheless:

>>> vars(t)
{'0potato': 123}

允许这样做的原因是什么?带有空格,空字符串,python保留关键字等属性的确有有效的用例吗?我以为原因是属性只是对象/命名空间dict中的键,但这是没有道理的,因为不允许使用其他有效的dict键的对象:

What is the reason for this being permissable? Is there really any valid use-case for attributes with spaces, empty string, python reserved keywords etc? I thought the reason was that attributes were just keys in the object/namespace dict, but this makes no sense because other objects which are valid dict keys are not allowed:

>>> setattr(t, ('tuple',), 321)
TypeError: attribute name must be string, not 'tuple'

推荐答案

The details from a comment on the post fully answer this question, so I'm posting it as an answer:

Guido 说:

...这是一个功能,您可以使用任意字符串 与getattr()和setattr()一起使用.但是,这些功能应该(并且可以!) 拒绝非字符串.

...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关键字冲突).因此,该论点似乎没有充分的理由禁止它.

Possible use-cases include hiding attributes from regular dotted access, and making attributes in correspondence with external data sources (which may clash with Python keywords). So, the argument seems to be there's simply no good reason to forbid it.

由于不允许非字符串的原因,这似乎是一个明智的限制,它可以确保实现的更高性能:

As for a reason to disallow non-strings, this seems to be a sensible restriction which is ensuring greater performance of the implementation:

尽管Python的字典已经有一些仅用于字符串的优化-一旦第一个非关键字符串显示出来,它们就动态地适应了一种更通用且稍慢的方法.

Although Python's dicts already have some string-only optimizations -- they just dynamically adapt to a more generic and slightly slower approach once the first non-key string shows up.

这篇关于不是有效的python标识符的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆