0

I have a class with many functions. Of these many functions, there's one which is pretty long and significant, and for readability purposes I'd like to have it on a separate py file. I would like on this separate file to keep using self.attribute notation.

For example, file1:

class something:
    def __init__(self):
        self.a=1
    def fun(self):
        run file2

file2:

  def fun_in_file2(self):
      self.a=3

Thanks for any help.

yonatan
  • 113
  • 9
  • 1
    Does this answer your question? [How can I separate the functions of a class into multiple files?](https://stackoverflow.com/questions/47561840/how-can-i-separate-the-functions-of-a-class-into-multiple-files) – Aleksander Ikleiw Jun 29 '22 at 11:15

1 Answers1

0

Technically, importing a function directly into a class will add it to the class:

class something:

    from file2 import fun_in_file2

    def __init__(self):
        self.a=1

    def fun(self):
        run file2
    
    def use_fun_in_file2(self):  # not necessary, just an example
        self.fun_in_file2()

I added an example how to call the imported function inside the class.

This is not very pretty but it should work with the self syntax although some IDEs might show a warning about it.

Another option is to inherit from another class that has the method you want.

SiP
  • 1,080
  • 3
  • 8