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
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With