类的构造函数通常会接受它的参数并将它们保存在实例中。例如:
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/