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()
相關文章
相關標籤/搜索