python非法的标识符,不是有效的python标识符的属性

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

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

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

>>> vars(t)

{'0potato': 123}

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 says:

...it is a feature that you can use any arbitrary string

with getattr() and setattr(). However these functions should (and do!)

reject non-strings.

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:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值