int()是一个独立的函数,还是它实际上是盖下的int类的一个_init_构造函数?

问题描述 投票:0回答:1

(a)我想弄清楚,到底是 int(), float(), tuple() 和类似的函数都是独立的functons,或者它们的工作方式就像用户类的构造函数一样(即调用类的 __init__() 方法的掩护下)。)

(b) 我想找到这些方法的可用签名,如 int(str), int(str, base).

(c) 我试着在github上偷看源代码,但它似乎是在c层实现的,而不是在Python层。甚至没有类似头的Python存根代码。

python python-3.x int sys
1个回答
0
投票

是的,所有这些都是类,它们是类对象。它们的 typetype 本身,就是一个类,一个元类)。

>>> type(int)
<class 'type'>

和自定义类一样。

>>> class Foo: pass
...
>>> type(Foo)
<class 'type'>

而且看起来很矛盾:

>>> type(type)
<class 'type'>

注意: 这些对象是 __init__. 那是一种特殊的方法 被称为 的构造函数来运行自定义初始化。即

>>> Foo.__init__ is Foo
False

1
投票

如果你使用 help(int) 你会看到这是一个类的名字。

Help on class int in module builtins:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer

但是,如果你再往下看,你不会看到一个... __init__ 方法。实例由内部C代码在 __new__ 类的方法。

© www.soinside.com 2019 - 2024. All rights reserved.