Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing methods for a Python class

I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this:

main_module.py:

class Instrument(Object):
    # Some import statement?
    def __init__(self):
        self.flag = True
    def direct_method(self,arg1):
        self.external_method(arg1, arg2)

to_import_from.py:

def external_method(self, arg1, arg2):
    if self.flag:
        #doing something
#...many more methods

In my case, to_import_from.py is machine-generated, and contains many methods. I would rather not copy-paste these into main_module.py or import them one by one, but have them all recognized as methods of the Instrument class, just as if they had been defined there:

>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)

Thanks!

like image 421
Martin Gustafsson Avatar asked Jun 29 '09 12:06

Martin Gustafsson


1 Answers

People seem to be overthinking this. Methods are just function valued local variables in class construction scope. So the following works fine:

class Instrument(Object):
    # load external methods
    from to_import_from import *

    def __init__(self):
        self.flag = True
    def direct_method(self,arg1):
        self.external_method(arg1, arg2)
like image 152
Ants Aasma Avatar answered Sep 24 '22 15:09

Ants Aasma