How to move the internal class’s code to a different file (Python)?

Suppose I have an inner class:

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

I want to implement class B in a different file from the class A code to improve readability.

How to achieve this Target?

Edit: I don’t want B to access in any way other than AB.

You can do this:

b_class.py:

class _B:
...

< p>a_class.py:

import b_class

class A:
B = b_class._B
...< /pre>

One of the principles of Pythonic OOP is "we all agree with adults here". This means you usually don't want to force hiding information. Leading underscores used to mean "don't use it", but they won't prevent Things that are accessed.

Although usually you don’t need to nest classes like this. What do you want to do? There may be a better solution.

Suppose I have a class with an inner class:

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

I want to implement class B in a different file from class A code to improve readability .

How to achieve this goal?

Edit: I don’t want B to access in any way other than AB.

You can 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 It’s "we all agree with adults here". This means that you generally don’t want to force hiding information. Leading underscores used to mean "don’t use it", but they won’t prevent things from being accessed.

Although usually you don't need to nest classes like this. What do you want to do? There may be a better solution.

Leave a Comment

Your email address will not be published.