为什么从文件中导入的 class 的整个代码都在调用者文件中执行?

Why the entire code of the imported class from the file is getting executed in the caller file?

class 被调用是从 prg.py 文件

进行测试
class Testing:

    def __init__(self, name):
        self.name = name

    @staticmethod
    def print_something():
        print("Class name: " + str(__class__))
arr = [2, 3, 9]


def adding(arr):
    i = len(arr) - 1
    while i >= 0:
        arr[i] += 1
        if arr[i] == 10:
            arr[i] = 0
            i -= 1
        else:
            break
    if i == -1:
        arr.insert(0, 1)
    return arr


print(adding(arr))

count = 1


def doThis():
    global count  # global keyword will now make the count variable as global
    for i in (1, 2, 3):
        count += 1


doThis()
print(count)

for i in range(10):
    if i == 5:
        break
    else:
        print(i)
else:
    print("Here")

调用文件为test.py,其代码如下

from prg import Testing

t = Testing("t2")
t.print_something()

执行test.py时的输出如下

[2, 4, 0]
4
0
1
2
3
4
Class name: <class 'prg.Testing'>

我需要做什么才能确保只有测试 class 下的代码而不是整个 prg.py 文件执行?

您在顶层有类似 print(adding(arr)) 的内容。这就是为什么。

解决该问题的流行方法是像这样格式化您的代码:

class Testing:
    pass

# Other classes and functions 

def main():
   # Whatever you need to test this particular script goes here

if __name__=="__main__":
    main()

现在如果你使用

from prg import Testing

你不会打印任何东西,因为现在 __name__prg 当 python 尝试导入 class Testing