Quentin Hayot
Quentin Hayot

Reputation: 7876

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

   ...

Upvotes: 0

Views: 211

Answers (2)

Andrew Johnson
Andrew Johnson

Reputation: 3186

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

Upvotes: 0

katerinah
katerinah

Reputation: 111

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.

Upvotes: 1

Related Questions