python中不同文件中函数和类的调用

  最近在学习Python的时候,遇到了一个不同文件中类无法调用的问题,搜了很多,发现很多人针对

这个问题都说的相当含糊,让我费了好大劲才把这个东东搞明白。记录一下,权且温习。

  调用分两种,一种是同种文件路径下的调用,这种一般的方法是:

  比如,文件b.py 调用a.py中的函数testa():

  方法一:

  from a import *

  testa()

  方法二:

  import a

  a.testa()

  栗子:

  文件aQueue.py

class QueueA:
        def __init__(self):
                self.items = []
        def is_empty(self):
                return self.items == []
        def enqueue(self, item):
                self.items.insert(0,item)
        def dequeue(self):
                return self.items.pop() 
        def size(self):
                return len(self.items)

  文件afunc.py

def test_call_file(input1,input2):
        print("file is afunc")
        input1 = input2 + 1
        print("inputa:%d inputb:%d"%(input1,input2))

  文件b.py的调用:

  

from aQueue import *
from afunc import *
q = QueueA()
q.enqueue('hello')
q.enqueue('hello')
q.enqueue('hello')
q.enqueue('hello')
print q.size()
          
test_call_file(2,3)

  文件c.py的调用:

import afunc
import aQueue
q = aQueue.QueueA()
q.enqueue('hello')
q.enqueue('hello')
q.enqueue('hello')
q.enqueue('hello')
print q.size()

afunc.test_call_file(2,3)

  不同文件路径下的调用:

  import sys

       sys.path.append('adress_of_B') #adress_of_B 表示文件B的地址

     import b

        b.fun()

  实例和上面差不多,只需要把目录换一下就行了。这里就不贴了。

  

原文地址:https://www.cnblogs.com/dylancao/p/8079129.html