class是python语言关键字吗_为什么不能属性名称是Python的关键字?

There is a restriction on the syntax of attribute access, in Python (at least in the CPython 2.7.2 implementation):

>>> class C(object): pass

>>> o = C()

>>> o.x = 123 # Works

>>> o.if = 123

o.if = 123

^

SyntaxError: invalid syntax

My question is twofold:

Is there a fundamental reason why using Python keyword attribute names (as in o.if = 123) is forbidden?

Is/where is the above restriction on attribute names documented?

It would make sense to do o.class = …, in one of my programs, and I am a little disappointed not to be able to do it (o.class_ would work, but it does not look as simple).

PS: The problem is obviously that if and class are Python keywords. The question is why using keywords as attribute names would be forbidden (I don't see any ambiguity in the expression o.class = 123), and whether this is documented.

解决方案

Because parser is simpler when keywords are always keywords, and not contextual (e.g. if is a keyword when on the statement level, but just an identifier when inside an expression — for if it'd be double hard because of X if C else Y, and for is used in list comprehensions and generator expressions).

So the code doesn't even get to the point where there's attribute access, it's simply rejected by the parser, just like incorrect indentation (which is why it's a SyntaxError, and not AttributeError or something). It doesn't differentiate whether you use if as an attribute name, a variable name, a function name, or a type name. It can never be an identifier, simply because parser always assigns it "keyword" label and makes it a different token than identifiers.

It's the same in most languages, and language grammar (+ lexer specification) is the documentation for that. Language spec mentions it explicitly. It also doesn't change in Python 3.

Also, just because you can use setattr or __dict__ to make an attribute with a reserved name, doesn't mean you should. Don't force yourself/API user to use getattr instead of natural attribute access. getattr should be reserved for when access to a variable attribute name is needed.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值