简体   繁体   中英

Initializing global variables using Python 3 import

What I'm trying to do may be easier to explain by example. Consider the following code:

In file my_custom_module.py

def oop_type_a():
    __init__(self):
    # class definitions, etc...

def oop_type_b():
    __init__(self):
    # class definitions, etc...

def define_a_bunch_of_oop_variables():
    global oop1
    global oop2

    oop1 = oop_type_a()
    oop2 = oop_type_b()

Using this file, I can run these commands:

>>>import my_custom_module
>>>my_custom_module.define_a_bunch_of_oop_variables()
>>>from my_custom_module import *

>>>oop1
<my_custom_module.oop_type_a object at 0x000000000615F470>
>>>oop2
<my_custom_module.oop_type_a object at 0x000000000615F5C0>

Is there a way to get this same functionality without the from my_custom_module import * ? What is the pythonic way to achieve this?

I have several objects that I need to initialize everytime I use this module, and doing this is tedious:

>>>import my_custom_module
>>>oop1 = my_custom_module.oop_type_a()
>>>oop2 = my_custom_module.oop_type_b()

The module is used to separate variables and methods. If you insist maybe you can try make a package and declare the global variables in __init__.py

refer this: Can I use __init__.py to define global variables?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM