问题描述
可能的重复:
访问python int文字方法
Python 中的一切都是对象.即使是数字也是一个对象:
>>>a=1>>>类型(一)<类'int'>>>>a.real1我尝试了以下方法,因为我们应该能够访问对象的类成员:
>>>类型(1)<类'int'>>>>1.真实文件<stdin>",第 1 行1.真实^语法错误:无效语法为什么这不起作用?
是的,整数文字是 Python 中的对象.总而言之,解析器需要能够理解它正在处理一个整数类型的对象,而语句 1.real
使解析器误以为它有一个浮点 1.
code> 后跟单词 real
,因此会引发语法错误.
要测试这个,你也可以试试
>>(1).真实1
还有,
>>1.0.real1.0
所以在 1.real
的情况下,python 将 .
解释为小数点.
编辑
BasicWolf 也说得很好 - 1.
被解释为 1 的浮点表示,所以 1.real
等价于编写 (1.)real
- 所以没有属性访问运算符,即句号/句号.因此语法错误.
进一步编辑
正如 mgilson 在他/她的评论中提到的那样:解析器可以处理对 int
的属性和方法的访问,但前提是该语句清楚地表明它被赋予了一个 int
而不是 float
.
Everything in Python is an object. Even a number is an object:
>>> a=1
>>> type(a)
<class 'int'>
>>>a.real
1
I tried the following, because we should be able to access class members of an object:
>>> type(1)
<class 'int'>
>>> 1.real
File "<stdin>", line 1
1.real
^
SyntaxError: invalid syntax
Why does this not work?
Yes, an integer literal is an object in Python. To summarize, the parser needs to be able to understand it is dealing with an object of type integer, while the statement 1.real
confuses the parser into thinking it has a float 1.
followed by the word real
, and therefore raises a syntax error.
To test this you can also try
>> (1).real
1
as well as,
>> 1.0.real
1.0
so in the case of 1.real
python is interpreting the .
as a decimal point.
Edit
BasicWolf puts it nicely too - 1.
is being interpreted as the floating point representation of 1, so 1.real
is equivalent to writing (1.)real
- so with no attribute access operator i.e. period /full stop. Hence the syntax error.
Further edit
As mgilson alludes to in his/her comment: the parser can handle access to int
's attributes and methods, but only as long the statement makes it clear that it is being given an int
and not a float
.
这篇关于整数文字是 Python 中的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!