'Python objects in other classes or separate?

I have an application I'm working on in Python 2.7 which has several classes that need to interact with each other before returning everything back to the main program for output.

A brief example of the code would be:

class foo_network():
    """Handles all network functionality"""
    def net_connect(self, network):
       """Connects to the network destination"""
       pass

class foo_fileparsing():
    """Handles all sanitation, formatting, and parsing on received file"""
    def file_check(self, file):
        """checks file for potential problems"""
        pass

Currently I have a main file/function which instantiates all the classes and then handles passing data back and forth, as necessary, between them and their methods. However this seems a bit clumsy.

As such I'm wondering two things:

  1. What would be the most 'Pythonic' way to handle this?
  2. What is the best way to handle this for performance and memory usage?

I'm wondering if I should just instantiate objects of one class inside another (from the example, say, creating a foo_fileparsing object within the foo_network class if that is the only class which will be calling it, rather than my current approach of returning everything to the main function and passing it between objects that way.

Unfortunately I can't find a PEP or other resource that seems to address this type of situation.



Solution 1:[1]

You can use modules. And have every class in one module. and then you can use import to import only a particular method from that class.

And all you need to do for that is create a directory with the name same as you class name and put a __init__.py file in that directory which tells python to consider that directory as a module.

Then for example the foo_network folder contains a file named foo_network.py and a file __init__.py and in foo_network.py the code is

class foo_network():
    """Handles all network functionality"""
    def net_connect(self, network):
       """Connects to the network destination"""
       pass

and in any other file you can simply use

import net_connect from foo_network

it will only import that particular method. This way your code will not look messy and you can will be importing only what is required.

You can also do

from foo_network import *

to import all methods at once.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mkrieger1