mercredi 10 juin 2020

How to make class objects available in other classes?

For example, I have the following file structure:

/project
├── module
│   ├── __init__.py
│   ├── file_1.py
│   └── file_2.py
├── app.py
├── config.json

In file_1 and file_2, I have classes with various functions that are configured when importing a module into an __init__.py:

import logging
from os import path, pardir

from module.file_1 import FooClass
from module.file_2 import BarClass

module_dir = path.abspath(path.dirname(__file__))
base_dir = path.abspath(path.join(module_dir, pardir))

logging.basicConfig(
    handlers=[logging.FileHandler(f'{base_dir}/project.log', 'a', 'utf-8')],
    level=logging.INFO,
    format='%(asctime)s:%(levelname)s:%(message)s'
)

config = json.loads(open(path.join(base_dir, 'config.json'), 'r').read())

foo_funcs = FooClass(logging, config)
bar_funcs = BarClass(logging, config)

So when I import this module into app.py, The functions foo_funcs and bar_funcs will already be configured. But what if the FooClass has methods that BarClass needs? If I import it into BarClass, then I will need to initialize it again, and I don’t need it, if I import the whole module into BarClass, then initialization will happen, but I don’t need it as I said.

So: how to make an object of FooClass, which I initialized in the file __init__.py(foo_funcs) available in the BarClass? I know that I can pass it as a parameter when initializing the object, but is there another way?

Aucun commentaire:

Enregistrer un commentaire