Python将类属性导入方法本地命名空间 [英] Python importing class attributes into method local namespace
问题描述
我一直想知道一会儿,如果有更容易的方法来分配类属性到方法的局部命名空间。例如,在 dosomething
方法中,我明确引用 self.a
和 self。 b
:
I have been wondering for a while if there is easier way to assign class attributes to method local namespace. For example, in dosomething
method, I explicitly make references to self.a
and self.b
:
class test:
def __init__(self):
self.a = 10
self.b = 20
def dosomething(self):
a = self.a
b = self.b
return(a + b)
但有时候我有很多变量输入并查看 - 我会在方法开头有一堆 var = self.var
语句。
But sometimes I have a lot of variables (more than 10) and it gets messy to type and look at - I would have bunch of var = self.var
statements at the beginning of a method.
有没有办法做这个更紧凑的方式? (我知道更新 local()
不是一个好主意)
Is there any way to do this more compact way? (I know updating local()
is not a good idea)
编辑:理想情况下,
def dosomething(self):
populate_local_namespace('a', 'b')
return(a + b)
推荐答案
Q.有什么方法可以做这个更紧凑的方式吗?
Q. Is there any way to do this more compact way?
1。 ,那么合理的Pythonic就可以将一个多变量访问器方法解析出来:
1. If the variables are read-only, it would be reasonably Pythonic to factor-out a multi-variable accessor method:
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代码的正常方式,通常是大多数人期望的方式。
If the variables aren't read-only, it is best to stick with self.inst_var = value
. That is the normal way to write Python code and is usually what most people expect.
strong>一段时间后,你会看到人们用较短的变量名缩写 self
。当使用非标准变量名称的可读性成本超过可读性成本时,使用此方法:
2. Once in a while you will see people abbreviate self
with a shorter variable name. It is used when the readability benefits of decluttering outweigh the readability cost of using a non-standard variable name:
def updatesomethings(s):
s.a, s.b, s.c = s.a + s.c, s.b - s.a, s.c * s.b
< hr>
3。另一种处理大量实例变量的方法是将它们存储在一个可变容器中,以方便打包和解包:
3. Another way to handle a very large number instance variable is to store them in a mutable container for ease of packing and unpacking:
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。还有一种字典操作方法可以工作,但它有一个代码气味,大多数Pythonistas将避免:
4. There is also a dictionary manipulation approach that would work, but it has a code smell that most Pythonistas would avoid:
def updatesomethings(self):
a = 100
b = 200
c = 300
vars(self).update(locals())
del self.self
这篇关于Python将类属性导入方法本地命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!