在对象中实现打包/解包 [英] Implement packing/unpacking in an object

查看:39
本文介绍了在对象中实现打包/解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个只包含属性的类,我想打包/解包来处理它.我应该实施什么 collections.abc 来获得这种行为?

I have a class that only contains attributes and I would like packing/unpacking to work on it. What collections.abc should I implement to get this behaviour?

class Item(object):

    def __init__(self, name, age, gender)
        self.name = name
        self.age = age
        self.gender = gender

a, b, c = Item("Henry", 90, "male")

我想避免使用 namedtuple.

推荐答案

您可以解压任何 可迭代.这意味着您需要实现 __iter__ 方法,并返回一个迭代器.在您的情况下,这可能只是:

You can unpack any Iterable. This means you need to implement the __iter__ method, and return an iterator. In your case, this could simply be:

def __iter__(self):
    return iter((self.name, self.age, self.gender))

或者,您可以将您的类设为 Iterator,然后 __iter__return self 并且你需要实现 __next__;这是更多的工作,可能不值得付出努力.

Alternatively you could make your class an Iterator, then __iter__ would return self and you'd need to implement __next__; this is more work, and probably not worth the effort.

有关详细信息,请参阅Python 的迭代器、可迭代和迭代协议究竟是什么?

根据我上面链接的问题,您还可以使用 __getitem__ 实现迭代:

Per the question I linked above, you could also implement an iterable with __getitem__:

def __getitem__(self, index):
    return (self.name, self.age, self.gender)[index]

这篇关于在对象中实现打包/解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆