为什么Python标准库中的方法可以作为函数调用?

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

我是Python的初学者,发现一个奇怪的现象,Python标准库中的一些方法可以作为函数调用。 例如,模块random.py中的类Random中定义了一个方法randint()。 据我了解,当我们想要调用它时,我们应该先导入模块random,然后声明类Random的实例,以便可以调用方法randint(),例如

import random as rd
aaa = rd.Random()
aaa.randint()

但是我发现randint()可以作为函数调用,不需要像上面那样做:

import random as rd
rd.randint()

所以我想知道这种不合逻辑的现象是怎么发生的?

为什么Python标准库中的方法可以作为函数调用?

python function class methods
1个回答
1
投票

查看

random.py
,我们看到实际上创建了一个实例,并将其方法导出为模块级函数。这没什么神奇的。

那里的评论描述得很漂亮:

# Create one instance, seeded from current time, and export its methods
# as module-level functions.  The functions share state across all uses
# (both in the user's code and in the Python libraries), but that's fine
# for most programs and is easier for the casual user than making them
# instantiate their own Random() instance.

_inst = Random()
# .. SNIP ..
randint = _inst.randint
© www.soinside.com 2019 - 2024. All rights reserved.