1

In Python, we cannot save class method's definition outside of class definition itself (as I understand it) because there is no concept of declaration. However, I wonder whether it is possible that I can include source code of method implementation saved in a standalone file, namely having the interpreter replace the piece of code in question. But as I have never seen such thing, this is probably not idiomatic in Python. Then how do you deal with the irritation that a class definition will be extremely long? Please correct me since I am new to Python, and find it quite different from C++.

class Foo
   def bar():
      # How to include definition saved in another file?
Violapterin
  • 337
  • 2
  • 14
  • look here: https://stackoverflow.com/questions/2864366/are-classes-in-python-in-different-files – fecub Jun 09 '17 at 08:53

2 Answers2

1
import another_file

class Foo
   def bar():
      another_file.class_name/def_name ...

or import just particular definition

from another_file import def_name

class Foo
   def bar():
      def_name ...
anatol
  • 791
  • 9
  • 16
1

Can do!

First solution

bar.py

def bar(foo):
    print foo

foo.py

from bar import bar as foo_bar

class Foo:
    bar = foo_bar

Alternative solution

bar.py

def bar(foo):
    print foo

foo.py

from bar import bar as foo_bar

class Foo:
    def bar(self, *args, **kwargs):
        return foo_bar(self, *args, **kwargs)
Mathieu Rodic
  • 6,637
  • 2
  • 43
  • 49