简体   繁体   中英

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. 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).

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.

Also, python lets you pull in from other files with the import statement.

Although there are several ways to do this, the first one I would recommend is to create mixin classes from both files.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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