Q. Is there any way to do this more compact way?
1.如果变量是只读的,那么将多变量访问器方法分解出来是合理的python方法:class Test:
def __init__(self):
self.a = 10
self.b = 20
self.c = 30
def _read_vars(self):
return self.a, self.b, self.c
def dosomething(self):
a, b, c = self._read_vars()
return a + b * c
def dosomethingelse(self):
a, b, c = self._read_vars()
return a - b * c
如果变量不是只读的,最好使用self.inst_var = value。这是编写Python代码的正常方式,通常也是大多数人所期望的。在
2.偶尔你会看到人们用更短的变量名来缩写self。当分离的可读性优势大于使用非标准变量名的可读性成本时,使用该变量名:
^{pr2}$
3.另一种处理大量实例变量的方法是将它们存储在可变容器中,以便于打包和拆包:class Test:
def __init__(self, a, b, c, d, e, f, g, h, i):
self._vars = [a, b, c, d, e, f, g, h, i]
def fancy_stuff(self):
a, b, c, d, e, f, g, h, i = self._vars
a += d * h - g
b -= e * f - c
g = a + b - i
self._vars[:] = a, b, c, d, e, f, g, h, i
4.还有一种字典操作方法可以工作,但它有一种大多数python爱好者都会避免的代码气味:def updatesomethings(self):
a = 100
b = 200
c = 300
vars(self).update(locals())
del self.self