python调用其他文件函数或类的示例

yipeiwu_com6年前Python基础

B.py调用A.py的函数或类

在同一个文件夹下

调用函数:

A.py文件:

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

B.py文件:

import A 
A.add(1,2) 

from A import add 
add(1,2) 

调用类:

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() 

import A 
a=A.A(2,3) 
a.add() 

在不同文件夹下

A.py文件的文件路径:E:\PythonProject\winycg

B.py文件:

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

附:如果在jupyter notebook引入py文件,有时需要重启一下;

以上这篇python调用其他文件函数或类的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python文件读写常见用法总结

1. 读取文件 # !/usr/bin/env python # -*- coding:utf-8 -*- """ 文件读取三步骤: 1.打开文件 f=open(file...

python实现比较两段文本不同之处的方法

本文实例讲述了python实现比较两段文本不同之处的方法。分享给大家供大家参考。具体实现方法如下: # find the difference between two texts #...

在python win系统下 打开TXT文件的实例

如下所示: fr=open("E:\Python\Test\datingTestSet.txt") arrayOLines = fr.readlines() open:打开文件 r...

python避免死锁方法实例分析

本文实例讲述了python避免死锁方法。分享给大家供大家参考。具体分析如下: 当两个或者更多的线程在等待资源的时候就会产生死锁,两个线程相互等待。 在本文实例中 thread1 等待th...

Python 列表的清空方式

情况列表的操作: del list[:] list=[] list[:]=[] def func(L): L....