python - 在 __init__ 函数中处理多个参数的优雅方式
问题描述
我有跟随 init 函数,它接收很多 args 来运行类(如果用户不输入任何内容或者可以是用户输入的值,则 args 是默认值)。在不失去可读性的情况下减少变量数量(不在 init 中显示很多 args)的最优雅的方法是什么?使用 *args 函数(如def__init__(self, *args))?
class World(object):
def __init__(self, grid_size=(GRID_WIDTH, GRID_HEIGHT),
cell_size=(CELL_WIDTH, CELL_HEIGHT),
obstacles_position= OBSTACLES,
recharge_position= RECHARGE_ZONE,
treadmill_position= TREADMILL_ZONE,
workers_positions= WORKERS_POS,
delivery_positions= DELIVERY_ZONE):
# some code bellow
def main():
# init some libraries
world = worldGrid()
# Do a while loop with the input variables from the world class
if __name__ = '__main__':
main()
Obs:我正在使用 Python 3+
解决方案
在我看来,您可能应该坚持使用函数头中的所有函数参数(就像您目前拥有的那样)。这使您的代码更具可读性,允许 Python 告诉您可能省略了哪些参数,与 Python 的内置help()
方法很好地配合,允许第三方 IDE 代码提示等,等等......
如果你真的想缩短函数头,你可以使用*args
and **kwargs
which 将接受任何可变参数,例如:
def func(self, *args, **kwargs):
print("args:", args)
print("kwargs:", kwargs)
用法如下所示:
>>> func(1, 2, 3, one="one", two="two")
args: (2, 3)
kwargs: {'one': 'one', 'two': 'two'}
因此,理论上您可以将您的类重构为如下所示。这段代码根本不处理默认值或任何错误检查——它只是将任何关键字参数设置为类本身的属性:
class World(object):
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
和用法:
>>> w = World(one=1, two=2, three=3)
>>> w.one
1
>>> w.two
2
>>> w.three
3
推荐阅读
- simulation - 在一定数量的滴答声后,如何开始在 Netlogo 中显示我的设置?
- sql - Redshift CTAS 和 IDENTITY 列
- wildfly - 从 DLQ 重新传递 JMS 消息
- constraints - pyomo 是否会删除它认为不需要的括号?
- jquery - 显示 JSON 对象数组中的元素
- python - Heroku 上的 Flask-Firebase 应用程序没有获取环境变量
- excel - UsedRange 循环比预期大
- mysql-workbench - 销售后更新库存水平的触发器
- c# - 搜索两个日期并使用 xml 文件中的日期填充 DataGridView
- reactjs - 如何在带有打字稿的反应应用程序中使用“位构建”