![](/img/trans.png)
[英]How to import class with all functions in Python from different file?
[英]Import different functions from another file in Python?
我有一個通過Google App Engine托管的python主文件,但是,我的所有函數都定義在同一類中。 這顯然不是那么干凈,對於文件管理也沒有用。 如何將所有功能保存在不同的文件中,然后導入該文件以使用這些功能?
這是我的文件,它是基本的日期驗證器:
import webapp2
def valid_year(year):
if (year.isdigit()):
year = int(year)
if (year < 2030 and year > 1899):
return True
def valid_day(day):
if (day.isdigit()):
day = int(day)
if (day <= 31 and day > 0):
return True
def valid_month(month):
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December']
month_abbvs = dict((m[:3].lower(), m) for m in months)
if month:
short_month = month[:3].lower()
return month_abbvs.get(short_month)
form="""
<form method = "post">
<label>Month</label>
<input type = "text" name = "month">
<label>Day</label>
<input type = "text" name = "day">
<label>Year</label>
<input type = "text" name = "year"><br>
<input type="submit" value="Validate Date">
</form>
"""
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write(form)
def post(self):
Month_Test = valid_month(self.request.get('month'))
Day_Test = valid_day(self.request.get('day'))
Year_Test = valid_year(self.request.get('year'))
if not (Month_Test and Day_Test and Year_Test):
self.response.out.write(form)
else:
self.response.out.write("Thanks! That's a totally valid day!")
application = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
你可以將所有的日期相關的方法到一個文件名為date_utils.py
並導入date_utils
在當前文件為:
import date_utils
並在每個方法調用中,使用模塊名稱對其進行限定。 例如:
Month_Test = valid_month(self.request.get('month'))
現在變成:
Month_Test = date_utils.valid_month(self.request.get('month'))
請注意,僅當兩個文件都在同一目錄中時,這種在其他文件中導入方法的方法才有效。 如果您的項目結構是這樣的:
my_project
|__utils
| |__file_utils.py
|__my_module
|__main.py
並且要在main
file_utils
中包含方法, file_utils
必須確保my_project
在PYTHONPATH
。 只有這樣,您才能在main
進行導入,例如import utils.file_utils
或from utils.file_utils import read_file
。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.