0

例如,假设我有这个:

class RandomFunctions:
    def function_1:
        print('function 1 calling')

    def function_2:
        print('function_2 activated')

    def function_3:
        print('function_3 activated')

    def function_4:
        print('function_4 activated')

RandomFunctions().function_4()

要调用function_4,Python 是遍历类中的所有其他函数,检查它是否是正确的函数,还是直接调用它?

4

2 回答 2

5

function_4是一个类属性,其名称存储在实现映射协议的对象中。查找是通过对该对象的直接索引来完成的。不涉及迭代,定义函数的顺序在很大程度上是无关紧要的。

>>> type(RandomeFunctions.__dict__)
<class 'mappingproxy'>
>>> RandomFunctions.__dict__['function_4'] is RandomFunctions.function_4
True
于 2020-06-02T18:35:03.917 回答
-1

我做了一个小实验,结果如下:

from time import perf_counter

class RandomFunctions: # Defines 20000 functions
    for n in range(20000):
        exec(f"""def function_{n}(self):
            print(f'function {n} calling')""")

a = RandomFunctions()
start = perf_counter()
a.function_0() # Calls first function
end = perf_counter()
print(end-start)

输出:

function 0 calling
0.03125423399999949

#

start = perf_counter()
a.function_1999() # Calls the 1999th function
end = perf_counter()
print(end-start)

输出:

function 1999 calling
0.0849990759999999

这个实验的结论似乎是:

该类确实遍历函数以找到正确的函数。

于 2020-06-02T18:44:44.543 回答