python调用其余文件的类和函数

在同一个文件夹下

调用函数

source.py文件:app

def func():
    pass

new.py文件:函数

import source
# 或者
from  source import func

调用类

Student.py文件:学习

class Student:
    def __init__(self, name, age, sex):
        self name = name
        self age = age
        self sex =sex

    def learn(self):
        print("学生学习!")

handler.py文件:spa

from Student import Student
s = Student('egon', 18, 'male')
s.learn()

# 或者
import Student
s = Student.Student('jack', 28, 'male')
s.learn()
在不一样一个文件夹下

因为Python import模块时,是在sys.path里按顺序查找的。须要先将要使用文件的文件路径加入sys.path中。code

import sys
sys.path.appent(r'/home/admin/PythonProject/CourseSelesct/')
import Student

s = Student.Student('egon', 18, 'male')
s.learn()
相关文章
相关标签/搜索