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

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

问题描述

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

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.

推荐答案

最Python化的方式就是您已经编写的内容.如果您很乐意要求使用命名参数,则可以执行以下操作:

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)

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

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