![](/img/trans.png)
[英]How to include class from another file(in another folder) - python
[英]Include functions in class from another file in python
我正在為 Django 編寫一個 SOAP Web 服務,它將有很多功能。 為了保持干凈,我想把它分成幾個文件。
我如何將我的函數代碼“包含”到我的類中(就像在 PHP 中一樣)。
例如:
class SOAPService(ServiceBase):
#first file
from myfunctions1 import *
#second file
from myfunctionsA import *
應該表現得像:
class SOAPService(ServiceBase):
#first file
def myfunction1(ctx):
return
def myfunction2(ctx, arg1):
return
#second file
def myfunctionA(ctx):
return
def myfunctionB(ctx, arg1):
return
...
Python 允許您從多個類繼承,因此繼續將您的方法放入一個單獨的基類並從中繼承。
此外,python 允許您使用 import 語句從其他文件中提取。
盡管有多種方法可以做到這一點,但我推薦的第一種方法是從兩個文件創建mixin類。
所以在你的主模塊中
import myfunctions1
import myfunctionsA
class SOAPService(ServiceBase,myfunctions1.mixin,myfunctionsA.mixin):
pass
並在您包含的模塊 myfunctions1、myfunctionA 等中。
class mixin:
def myfunction1(self):
return
def myfunction2(self, arg1):
return
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.