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?
-
1Having 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?jonrsharpe– jonrsharpe2014年01月28日 16:19:14 +00:00Commented 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?Robᵩ– Robᵩ2014年01月28日 16:22:43 +00:00Commented Jan 28, 2014 at 16:22
1 Answer 1
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.
4 Comments
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.