python调用其他文件中的函数或者类

  • Post author:
  • Post category:python



1 .在同一个文件夹下,调用函数或者类

A.py文件中

def test():
	print('this is test func')

class A:
    def test():
        print('this is a class named A, its func is test() ')

B.py文件中

# way 1
from A import test
from A import A

test()

a = A()
a.test()


# way 2
import A
A.test()
a = A.A()
a.test()


2 .在不同文件夹下,调用函数或者类

src文件夹与B.py文件在同一目录下,src文件夹下有C.py文件

C.py文件中

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def test():
	print('this is test func')

class C:
    def test(self):
        print('this is a class named C, its func is test() ')        

B.py文件中

from src.C import test
from src.C import C

test()

a = C()
a.test()