如何避免过多的参数传递?

Vin*_*nce 3 python design-patterns

我正在开发一个跨越5个模块的python的中型程序.程序在主模块中使用OptionParser接受命令行参数,例如main.py. 这些选项稍后用于确定其他模块中的方法的行为(egapy,b.py).当我扩展用户自定义行为或程序的能力时,我发现我最终在a.py中的方法中要求这个用户定义的参数,而不是由main.py直接调用,而是由另一个调用a.py中的方法:

main.py:

 import a
 p = some_command_line_argument_value
 a.meth1(p)
Run Code Online (Sandbox Code Playgroud)

a.py:

meth1(p):
       # some code
       res = meth2(p)
       # some more code w/ res

meth2(p):
       # do something with p
Run Code Online (Sandbox Code Playgroud)

这种过多的参数传递似乎是浪费和错误的,但是我努力尝试我无法想到解决这个问题的设计模式.虽然我有一些正式的CS教育(在我的学士学位期间辅修CS),但自从我开始使用python以来,我才真正体会到良好的编码实践.请帮助我成为更好的程序员!

Dav*_*ler 8

创建与程序相关的类型的对象,并存储与每个对象相关的命令行选项.例:

import WidgetFrobnosticator
f = WidgetFrobnosticator()
f.allow_oncave_widgets = option_allow_concave_widgets
f.respect_weasel_pins = option_respect_weasel_pins

# Now the methods of WidgetFrobnosticator have access to your command-line parameters,
# in a way that's not dependent on the input format.

import PlatypusFactory
p = PlatypusFactory()
p.allow_parthenogenesis = option_allow_parthenogenesis
p.max_population = option_max_population

# The platypus factory knows about its own options, but not those of the WidgetFrobnosticator
# or vice versa.  This makes each class easier to read and implement.
Run Code Online (Sandbox Code Playgroud)