遍历构造函数的参数 [英] Iterating through constructor's arguments

查看:25
本文介绍了遍历构造函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己编写类构造函数是这样的:

I often find myself writing class constructors like this:

class foo:
    def __init__(self, arg1, arg2, arg3):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

如果参数(和类属性)的数量变多,这显然会变得很痛苦.我正在寻找最 Pythonic 的方式来循环遍历构造函数的参数列表并相应地分配属性.我正在使用 Python 2.7,所以理想情况下我正在寻找该版本的帮助.

This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.

推荐答案

最 Pythonic 的方式是您已经编写的内容.如果您愿意要求命名参数,您可以这样做:

The most Pythonic way is what you've already written. If you are happy to require named arguments, you could do this:

class foo:
    def __init__(self, **kwargs):
        vars(self).update(kwargs)

这篇关于遍历构造函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆