1

I want to implement a method for a class - the method will use the results of other methods in the class, but it will be 100s of lines long, so I would like to define the method in another file, if possible. How can I do this? Something like this:

ParentModule.py:

import function_defined_in_another_file
def method(self):
 return function_defined_in_another_file.function()

ParentModule is the main module which I don't want to define the function in.

function_defined_in_another_file.py:

import ParentModule
def function():
 a = ParentModule.some_method()
 b = ParentModule.some_other_method()
 return a + b 

The function that is defined in another file has to be able to use methods available from the ParentModule.

Is the way I've done it above appropriate, or is there a better way?

Martijn Pieters
1.1m326 gold badges4.2k silver badges3.5k bronze badges
asked Jan 28, 2014 at 16:15
2
  • 1
    Having a single methods 100s of lines long is a sign something is wrong - are there sections of it you could cut out into smaller methods or even standalone functions? Repetitions that could be simplified? Commented Jan 28, 2014 at 16:19
  • The title of your question says "method for class", but you haven't defined any classes. Are you really talking about methods or about stand-alone functions? Commented Jan 28, 2014 at 16:22

1 Answer 1

3

You could just assign the method to the class:

import function_defined_in_another_file
class SomeClass():
 method = function_defined_in_another_file.function

It'll be treated just like any other method; you can call method on instances of SomeClass(), other SomeClass() methods can call it with self.method(), and method() can call any SomeClass() method with self.method_name().

You do have to make sure that function() accepts a self argument.

answered Jan 28, 2014 at 16:17
Sign up to request clarification or add additional context in comments.

4 Comments

But then I would have to define the function in the ParentModule file? I want to define it in another file/module
@user1654183: sorry, had your modules mixed up
Thank you! that makes more sense. One last thing: "You do have to make sure that function() accepts a self argument." How exactly can I do that when the function is defined in another file not as part of a class?
@user1654183: just by adding self as the first argument. :-) The self parameter name is only a convention. It is by using a function as an attribute of a class that it becomes a method, and self is passed in.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.