简体   繁体   English

在 python 中的另一个文件中包含类中的函数

[英]Include functions in class from another file in python

I'm writing a SOAP web service for Django which will have a lot of functions.我正在为 Django 编写一个 SOAP Web 服务,它将有很多功能。 To keep it clean, I would like to split it in several files.为了保持干净,我想把它分成几个文件。

How do I "include" my functions code into my class (like in PHP).我如何将我的函数代码“包含”到我的类中(就像在 PHP 中一样)。

For example:例如:

class SOAPService(ServiceBase):
  #first file
  from myfunctions1 import *
  #second file
  from myfunctionsA import *

Should behave like:应该表现得像:

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 lets you inherit from multiple classes, so go ahead an put your methods into a separate base class and inherit from it, too. Python 允许您从多个类继承,因此继续将您的方法放入一个单独的基类并从中继承。

Also, python lets you pull in from other files with the import statement.此外,python 允许您使用 import 语句从其他文件中提取。

Although there are several ways to do this, the first one I would recommend is to create mixin classes from both files.尽管有多种方法可以做到这一点,但我推荐的第一种方法是从两个文件创建mixin类。

So in your main module所以在你的主模块中

import myfunctions1
import myfunctionsA
class SOAPService(ServiceBase,myfunctions1.mixin,myfunctionsA.mixin):
    pass

and in your included modules myfunctions1, myfunctionA etc.并在您包含的模块 myfunctions1、myfunctionA 等中。

class mixin:
    def myfunction1(self):
        return
    def myfunction2(self, arg1):
        return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM