简体   繁体   中英

Python's equivalence of using namespace

I have the following Helper.py python script

class Helper:
# Helper has many many classes! (AA, BB, CC, DD, ....) not just 2!
    class AA:
        CMD_AA = '8'
        CMD_AB = '1'

    class BB:
        CMD_BA = '0'
        CMD_BB = '1'

I created this helper file to make code more readable. So one can write this;

# this usage is more readable and makes sense
cmd.a = AA.CMD_AB 
cmd.b = BB.CMD_BB 

# instead of some thing like this where no one knows
# what 1 is interms of a or b!!
cmd.a = 1
cmd.b = 1

The helper script is imported in many python files! And the only way i know how to use it is as such

from Helper import *
cmd.a = Helper.AA.CMD_AA  # instead of cmd.a = 8
cmd.b = Helper.BB.CMD_BB  # instead of cmd.b = 1

Is there a way to get rid of the 'Helper.' I'm already adding more typing. So it'll look like;

from Helper import *

#in C++ u can use something like using namespace Helper;
cmd.a = AA.CMD_AA  # instead of cmd.a = 8
cmd.b = BB.CMD_BB  # instead of cmd.b = 1

you should just delete the wrapper Helper class and dedent the rest of the file ... the file itself provides the namespace if you want it

Helper.py

class CMD_AA:
    ...

main.py

import Helper
Helper.CMD_AA
# or just
from Helper import CMD_AA 

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