创建一个简单的oneoffpython对象的简单方法是什么?

2024-05-23 14:15:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个简单的一次性Python对象来保存一些命令行选项。我想这样做:

options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False

# Then, elsewhere in the code...
if options.VERBOSE:
    ...

当然,我可以使用字典,但是options.VERBOSEoptions['VERBOSE']更可读,也更容易输入。在

我认为我应该能做到

^{pr2}$

,因为object是所有类对象的基类型,因此应该类似于没有属性的类。但它不起作用,因为使用object()创建的对象没有__dict__成员,因此无法向其添加属性:

options.VERBOSE = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'

创建一个对象的最简单的“pythonic”方法是什么,最好不用创建额外的helper类?在


Tags: the对象命令行infalsetrueverbose属性
3条回答

collections module在2.6中增加了一个namedtuple函数:

import collections
opt=collections.namedtuple('options','VERBOSE IGNORE_WARNINGS')
myoptions=opt(True, False)

>>> myoptions
options(VERBOSE=True, IGNORE_WARNINGS=False)
>>> myoptions.VERBOSE
True

namedtuple是不可变的,因此您只能在创建它时分配字段值。在

在早期的Python版本中,可以创建一个空类:

^{2}$

根据您的要求,我认为定制类是您的最佳选择:

class options(object):
    VERBOSE = True
    IGNORE_WARNINGS = True

if options.VERBOSE:
    # ...

完整地说,另一种方法是使用一个单独的模块,即options.py来封装您的选项默认值。在

options.py

^{2}$

然后,在main.py中:

import options

if options.VERBOSE:
    # ...

这具有从脚本中清除一些混乱的特性。默认值很容易找到和更改,因为它们在自己的模块中被封锁。如果以后您的应用程序已经增长,您可以轻松地从其他模块访问选项。在

这是我经常使用的一种模式,如果您不介意您的应用程序变得比单个模块大的话,我会衷心推荐您使用。或者,从一个自定义类开始,如果你的应用程序扩展到多个模块,则以后再扩展到一个模块。在

为什么不直接使用optparse

from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
              help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
              action="store_false", dest="verbose", default=True,
              help="don't print status messages to stdout")

(options, args) = parser.parse_args()

file = options.filename
if options.quiet == True:
    [...]

相关问题 更多 >