Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class inheritance across files

Tags:

python

class

I'm struggling with some definition of inherited classes, accross multiple files.

I've searched for a long time, and found some examples, but none that solved my issue.

Let's dive into an example:

file1.py:

from file2 import SubClass

class MainClass:
  def __init__(self):
    print("This is MainClass")

mc = MainClass()
mc.SaySomething()

file2.py:

from file1 import MainClass

class SubClass(MainClass):
  def SaySomething(self):
    print("This is the subclass")

My goal is to split up a huge class into multiple files, each containing some related functions.

I've tried a lot of different combinations, but always get an error - it's different when I change something of course, but the result is the same; it doesn't work.

I guess it's related to the way I try to import each file into each other, but I haven't figured out how to do it, so I hope someone can solve it, and explain it to me.

Actually a third file is will import the main class and execute it. I guess that file only need to import file1.py, as it will import file2 - otherwise correct me, please.

Okay, so that's part one. However, I'm also curious if theres a way of which I can make some multiple nested modules/functions in the object - for the structures sake.

I'm quite sure an example will explain it better. Can I make something like:

mc = MainClass()
mc.SubClass.SaySomething()

...instead of just mc.SaySomething()? This way I can keep a way better structure of the code, I think.

like image 956
Kasper Leth Avatar asked Nov 20 '22 08:11

Kasper Leth


1 Answers

You could refactor your code to make multiple classes minimizing dependencies (as self-contained as they can get). Then instead of inheritance try composition. Which means employ duck typing instead of parent-child relations. The inheritance route won't work because that would mean weird circular imports. So,

# a.py
class A:
    # some code
# b.py
import a
class B:
    aobj = a.A()
    # go on using aobj

But, instead of all this you should always prefer revisiting your design, cleaning it up, so that it becomes more readable. Moreover it might also happen that the seemingly large class might be cleanly split in to multiple chunks, if parts of the code are found to be unrelated after some inspection.

like image 113
C Panda Avatar answered Mar 29 '23 23:03

C Panda