我正在构建一个包含大约一百个常量的Python模块.
当人们导入我的模块时,我想避免命名问题,所以我想知道最好的方法是什么.
MY_CONSTANT = 1
MY_SECOND_CONSTANT = 2
...
MY2_CONSTANT = "a"
MY2_SECOND_CONSTANT = "b"
...
Run Code Online (Sandbox Code Playgroud)
要么
class My:
CONSTANT = 1
SECOND_CONSTANT = 2
...
class My2
CONSTANT = "a"
SECOND_CONSTANT = "b"
...
Run Code Online (Sandbox Code Playgroud)
或许你的另一个建议?
来自Java,我当然更喜欢第二种方式,但有些人可能会觉得它有点过分......
小智 27
这得看情况.通常,常量是在模块级别定义的.但是,如果你有许多的常量category_a和category_b,它甚至可能是有意义的增加一个子包constants的模块constants.category_a和constants.category_b.
我会避免使用class- 它可能是实例化的,这是没有意义的,除了允许你将一个以上的物理文件填入一个物理文件之外它没有任何优势(如果有的话,你可能不应该这样做)这么多常数).Java版本可以使用静态类,但Python等价物是一个模块.
除了你之外,名字冲突在Python中不是问题import *- 但你不应该这样做.只要模块内部没有名称冲突,请放心,用户既不会将模块中的所有名称都拉出来,也不会以与其他模块冲突的名称导入.
Mic*_*zcz 24
每个模块都提供自己的命名空间,因此不需要创建另一个模块.
有模块foo.py:
FOO = 1
BAR = 2
SHMOO = 3Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
import foo
foo.BARRun Code Online (Sandbox Code Playgroud)
如果使用类,则可以禁止覆盖常量(或禁止向该类添加常量).使用类文件(模块)的另一个好处是,当你有许多组时,你不需要有很多文件.
所以它看起来像这样:
class MyConstBaseClass:
"""
forbids to overwrite existing variables
forbids to add new values if "locked" variable exists
"""
def __setattr__(self,name,value):
if(self.__dict__.has_key("locked")):
raise NameError("Class is locked can not add any attributes (%s)"%name)
if self.__dict__.has_key(name):
raise NameError("Can't rebind const(%s)"%name)
self.__dict__[name]=value
class MY_CONST_GRP1(MyConstBaseClass):
def __init__(self):
self.const1 = "g1c1"
self.const2 = "g1c2"
my_const_grp1 = MY_CONST_GRP1()
class MY_CONST_GRP2(MyConstBaseClass):
def __init__(self):
self.const1 = "g2c1"
self.const3 = "g2c3"
self.locked = 1 # this will create lock for adding constants
my_const_grp2 = MY_CONST_GRP2()
print my_const_grp1.const1 # prints "g1c1"
print my_const_grp1.const2 # prints "g1c2"
print my_const_grp2.const1 # prints "g2c1"
print my_const_grp2.const3 # prints "g2c3"
my_const_grp1.new_constant = "new value" #adding constants is allowed to this group
#my_const_grp1.const1 = "new value" #redefine would raise an error
#my_const_grp2.new_constant = "first value" #adding constant is also forbidden
#my_const_grp2.const1 = "new value" #redefine would raise an error
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40428 次 |
| 最近记录: |