python - 自动保存构造函数参数

标签 python constructor

类的构造函数通常会接受它的参数并将它们保存在实例中。例如:

class Example(object):
    def __init__(self, title='',backtitle='', height=20, width=50):
        self.title = title
        self.backtitle = backtitle
        self.height = height
        self.width = width

这是重复的,所以我创建了一个辅助函数来自动执行此操作:

from inspect import getargspec
def save_args(values):
    for i in getargspec(values['self'].__init__).args[1:]:
        values['self'].__dict__[i] = values[i]

class Example(object):
    def __init__(self, title='',backtitle='', height=20, width=50):
        save_args(vars())

我的问题如下:

  • 这会在某些类或参数上失败吗
  • 它可移植吗,它能在 Jython 上工作吗,等等。它对我来说在 python 2.7 和 3.2 上工作
  • 是否有更简单的替代方案?
  • 是否有一个 python 包已经可以做到这一点?

最佳答案

当你的类使用 __slots__ 时它会失败.你可以使用 setattr()相反:

from inspect import getargspec
def save_args(values):
    for i in getargspec(values['self'].__init__).args[1:]:
        setattr(values['self'], i, values[i])

前提是 __init__ 的 arguments 关键字参数当然都是已声明的插槽。

否则这应该适用于任何 Python 实现。

您可能对 previous discussion of the topic 感兴趣,引发了Python-ideas list thread .

关于python - 自动保存构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15484120/

相关文章:

c++ - 从 C++ 构造函数调用其他函数

java - 构造函数调用或 JFrame 的问题

c# - 使用从单个参数派生的两个参数调用基本构造函数

python - 仅使用不同颜色为 matplotlib barplot 中的某些条着色

Python - 在 return 内嵌套 if else

python - Seaborn自动选色

c# - 调用 this() 构造函数和不同的 base() 构造函数

c# - 创建构造函数时报错 "member names cannot be the same as their enclosing type"是什么意思,如何解决?

python - 使用 BeautifulSoup 从 HTML 中抓取数字

python - Pandas:为什么在 boolean 索引后需要双括号来选择列