[英]Unpacking instance variables by making container iterable
I just want to be able to unpack the instance variables of class foo, for example: 我只想能够解压缩foo类的实例变量,例如:
x = foo("name", "999", "24", "0.222")
a, b, c, d = *x
a, b, c, d = [*x]
I am not sure as to which is the correct method for doing so when implementing my own __iter__
method, however, the latter is the one that has worked with mixed "success". 我不确定在实现自己的
__iter__
方法时哪种方法正确,但是,后者是处理混合“成功”方法的方法。 I say mixed because doing so with the presented code appears to alter the original instance object x
, such that it is no longer valid. 我之所以说是混合的,是因为对所提供的代码执行此操作似乎会更改原始实例对象
x
,从而使其不再有效。
class foo:
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
def __iter__(self):
return iter([a, b, c, d])
I have read the myriad posts on this site regarding __iter__
, __next__
, generators etc., and also a python book and docs.python.org and seem unable to figure what I am not understanding. 我已经阅读了本网站上有关
__iter__
, __next__
,生成器等的大量文章,以及一本python书和docs.python.org,似乎无法弄清我的理解。 I've gathered that __iter__
needs to return an iterable (which can be just be self
, but I am not sure how that works for what I want). 我已经收集到
__iter__
需要返回一个可迭代的对象(它可以只是self
,但是我不确定这对于我想要的是如何工作的)。 I've also tried various ways of playing around with implementing __next__
and iterating over vars(foo).items()
, either by casting to a list or as a dictionary, with no success. 我还尝试了各种实现
__next__
并遍历vars(foo).items()
,这些方法通过转换为列表或作为字典都没有成功。
I don't believe this is a duplicate post on account that the only similar questions I've seen present a single list sequence object attribute or employ a range of numbers instead of a four non-container variables. 我不认为这是重复的帖子,因为我所看到的唯一类似的问题是呈现单个列表序列对象属性或采用一定范围的数字而不是四个非容器变量。
If you want the instance's variables, you should access them with .self
: 如果需要实例的变量,则应使用
.self
访问:
def __iter__(self):
return iter([self.a, self.b, self.c, self.d])
with this change, 有了这个改变,
a, b, c, d = list(x)
will get you the variables. 会给你变量。
You could go to the more risky method of using vars(x)
or x.__dict__
, sort it by the variables name (and that's why it is also a limited one, the variables are saved in no-order), and extract the second element of each tuple. 您可以使用使用
vars(x)
或x.__dict__
风险更高的方法,按变量名称对其进行排序(这就是为什么它也是一个有限的变量,变量以无序保存的原因),然后提取第二个变量每个元组的元素。 But I would say the iterator is definitely better. 但是我会说迭代器肯定更好。
You can store the arguments in an attribute ( self.e
below) or return them on function call: 您可以将参数存储在属性中(下面的
self.e
)或在函数调用时将其返回:
class foo:
def __init__(self, *args):
self.a, self.b, self.c, self.d = self.e = args
def __call__(self):
return self.e
x = foo("name", "999", "24", "0.222")
a, b, c, d = x.e
# or
a, b, c, d = x()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.