我有一个包含许多具有默认值的实例变量的类,可以选择在实例化中覆盖它(注意:没有可变的默认参数)。
由于self.x = x
多次编写等非常多余,因此我以编程方式初始化变量。
为了说明,考虑这个例子(为了简洁起见,它只有 5 个实例变量和省略了任何方法):
例子:
# The "painful" way
class A:
def __init__(self, a, b=2, c=3, d=4.5, e=5):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
# The "lazy" way
class B:
def __init__(self, a, b=2, c=3, d=4.5, e=5):
self.__dict__.update({k: v for k, v in locals().items() if k!='self'})
# The "better lazy" way suggested
class C:
def __init__(self, a, b=2, c=3, d=4.5, e=5):
for k, v in locals().items():
if k != 'self':
setattr(self, k, v)
x = A(1, c=7)
y = B(1, c=7)
z = C(1, c=7)
print(x.__dict__) # {'d': 4.5, 'c': 7, 'a': 1, 'b': 2, 'e': 5}
print(y.__dict__) # {'d': 4.5, 'c': 7, 'a': 1, 'b': 2, 'e': 5}
print(z.__dict__) # {'d': 4.5, 'c': 7, 'a': 1, 'b': 2, 'e': 5}
因此,为了让我的生活更轻松,我使用 B 类中显示的习语,它产生与 A 相同的结果。
这是不好的做法吗?有什么陷阱吗?
附录: 使用这个习语的另一个原因是为了节省一些空间——我打算在MicroPython中使用它。无论出于何种原因 因为当地人在那里的工作方式不同,所以只有 A 类中显示的方式在其中有效。