Python对象为什么可以再通过一个整数psented $ P $属性? [英] Why can a Python object have an attribute represented by an integer?

查看:172
本文介绍了Python对象为什么可以再通过一个整数psented $ P $属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我可能有一个什么样的蟒蛇属性实际上的一个根本性的误解是的。考虑以下几点:

I think I might have a fundamental misunderstanding of what a python attribute actually is. Consider the following:

 >>> class Test:
 ...     pass
 ... 
 >>> t = Test()
 >>> setattr(t, '0', 0)
 >>> t.0
   File "<stdin>", line 1
     t.0
       ^
 SyntaxError: invalid syntax
 >>> getattr(t, '0')
 0
 >>> setattr(t, 'one', 1)
 >>> t.one
 1
 >>> getattr(t, 'one')
 1

为什么Python的让我设置一个属性,如果我不能合法使用点表示法访问它?据我所知, t.0 是没有意义的,但在同一时间,我不知道为什么它没有比 t.one 因为我创造了他们以同样的方式。

Why does Python allow me to set an attribute if I can't legally access it with dot notation? I understand that t.0 makes no sense, but at the same time I wonder why it's no different than t.one because I created them the same way.

推荐答案

这仅仅是一个语法和Python的语义的怪癖。任何串可以被用作一个属性名称,但是只有标识符可以用点标记一起使用。因此,在访问非标识符属性的唯一方法是使用GETATTR / SETATTR或其他一些间接的作用。奇怪的是这种做法并不这么一直延伸到允许任何类型是一个属性,只有串得到特权。

This is just a quirk of the syntax and semantics of python. Any string can be used as an attribute name, however only identifiers can be used with dot notation. Thus the only way of accessing non-identifier attributes is with getattr/setattr or some other indirect function. Strangely enough this practice doesn't extend so far as to allow any type to be an attribute, only strings get that privilege.

这篇关于Python对象为什么可以再通过一个整数psented $ P $属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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