python: One .py file calls classes and functions in another .py file

in the same folder

- call function

  • method one

A.py:

def add(x,y):
    print('和为:%d'%(x+y))

B.py:

import A
A.add(1,2)
  • Method Two
from A import add
add(1,2)

-Call class

  • method one

A.py:

class A:
    def __init__(self,xx,yy):
        self.x=xx
        self.y=yy
    def add(self):
        print("x和y的和为:%d"%(self.x+self.y))

B.py:

from A import A
a=A(2,3)
a.add()
  • Method Two
import A
a=A.A(2,3)
a.add()

in the same folder

File path of A.py file: E:\PythonProject

B.py file:

'''
python import模块时, 是在sys.path里按顺序查找的。
sys.path是一个列表,里面以字符串的形式存储了许多路径。
使用A.py文件中的函数需要先将他的文件路径放到sys.path中
'''
import sys
sys.path.append(r'E:\PythonProject')
import A
 
a=A.A(2,3)
a.add()

Guess you like

Origin blog.csdn.net/m0_51662391/article/details/128260820