python - 访问文字上的属性适用于所有类型,但不适用于 `int` ;为什么?

标签 python python-2.7 python-3.x language-lawyer

我读过python中的一切都是一个对象,因此我开始尝试不同的类型并调用 __str__ 关于他们——起初我感到非常兴奋,但后来我感到困惑。

>>> "hello world".__str__()
'hello world'
>>> [].__str__()
'[]'
>>> 3.14.__str__()
'3.14'
>>> 3..__str__()
'3.0'
>>> 123.__str__()
  File "<stdin>", line 1
    123.__str__()
              ^
SyntaxError: invalid syntax
  • 为什么 <em>something</em>.__str__()int 之外的“一切”工作?
  • 123不是 int 类型的 对象 ?

最佳答案

你需要括号:

(4).__str__()

问题是词法分析器认为“4”。将是一个 float 。

另外,这可行:

x = 4
x.__str__()

关于python - 访问文字上的属性适用于所有类型,但不适用于 `int` ;为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33054229/

相关文章:

python - python脚本不会停止

python - Flask request.args.get 获取所有参数(Python)

python - 使用基数排序对负数和正数进行排序

python - 为什么 pandas dataframe 消耗的 RAM 比原始文本文件的大小多得多?

python - 生成器和协程的异步装饰器

python - macOS Sierra 安装 PyQt5 for python2.7

python - 如何在python中建立一个正规的表情符号词汇表?

Python Unicode 编码错误序号不在带欧元符号的 <128> 范围内

python - 只保留包含字符串列表中的字符串的 df 列值

python - pandas:二进制编码 pandas 列中的一组值