Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么从文件导入的类的整个代码都在调用方文件中执行?_Python_Class_Python Import - Fatal编程技术网

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

Python 为什么从文件导入的类的整个代码都在调用方文件中执行?,python,class,python-import,Python,Class,Python Import,正在调用的类正在从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 whil

正在调用的类正在从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()
[2, 4, 0]
4
0
1
2
3
4
Class name: <class 'prg.Testing'>
执行test.py时的输出如下

from prg import Testing

t = Testing("t2")
t.print_something()
[2, 4, 0]
4
0
1
2
3
4
Class name: <class 'prg.Testing'>
[2,4,0]
4.
0
1.
2.
3.
4.
类名:

为了确保只执行测试类下的代码而不执行整个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

您不会打印任何内容,因为现在当python尝试导入类
测试时,
\uu name\uu
prg
,您不能这样做。导入文件始终会执行文件中的所有代码,因为它无法知道要导入的名称需要哪些部分。如果不希望执行该文件,请不要将其放入顶级代码中,将其放入函数中。因此,我只需要在prg.py文件中包含与“测试”类相关的代码,并删除其他所有内容?或者将“其他所有内容”放入函数中,您可以根据需要执行该函数。在顶层有
print(adding(arr))
,这会导致该函数运行。把它和其他任何东西放在另一个函数中,或者
如果uuuu name\uuuuu==“uuuuu main\uuuuuuuuuuu”:
guard。谢谢Barmar和Carcigenicate。根据您的评论,我将剩下的代码移到了文件中一个单独的函数中,现在调用时只执行“测试”类代码。