Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move code of an inner class to different file (Python)?

Assume I have some class with an inner class:

class A:
   class B:
      ...
   ...

I would like to implement class B in a different file than the code for class A to increase readability.

How can this be accomplished?


EDIT: I don't want B to be accessible in any way other than A.B.

like image 218
R B Avatar asked Feb 15 '15 16:02

R B


2 Answers

You could do this:

b_class.py:

class _B:
    ...

a_class.py:

import b_class

class A:
    B = b_class._B
    ...

One of the principles of Pythonic OOP is "we're all consenting adults here". This means that you don't usually want to forcibly hide information. Leading underscores used to mean "don't use this", but they don't prevent things being accessed.

Although generally you don't need to nest classes like this. What do you want to do this for? There is probably a better solution.

like image 111
rlms Avatar answered Oct 01 '22 23:10

rlms


You seem to be working on a C++ namespace or Java package declaration principle which is not the Python model. The implementation of namespaces in Python is based the file name. Objects (classes, functions, etc.) are named by the source file that contains them.

You want HMM and HMM.State? Fine, do as sweeneyrod suggested and use the has-a object composition principle:

import states

class HMM {
    def __init__(self):
        self.markov_stuff = stuff
        self.state = states.State(more_stuff)
        …
}

That's how it works, where states.py contains the definition of class State.

If you want to make it look more "integrated" you could use from states import State yielding

from states import State

class HMM {
    def __init__(self):
        self.markov_stuff = stuff
        self.state = State(more_stuff)
        …
}

That gives you separate files: markov.py and states.py with the syntax of one less level of . indirection.

If you desire something else, either you get into confusing (and unconventional) module dictionary munging which is not recommended. Different languages allow expression of intent in different ways, and this is the pythonic way.

like image 22
msw Avatar answered Oct 01 '22 23:10

msw