user1654183
user1654183

Reputation: 4605

Defining a method for a class somewhere else

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?

Upvotes: 1

Views: 266

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121276

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.

Upvotes: 3

Related Questions