对象覆盖元组扩展的特殊方法? [英] special method for an object to override tuple expansion?

查看:60
本文介绍了对象覆盖元组扩展的特殊方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果标题不够清楚,我将提供一个有关问题的示例.

I will provide an example of the problem in question, in case the title was not clear enough.

比方说,我有一个class Point(object),它代表2d坐标. 是否可以创建一个魔术"方法来实现以下目的?

Let's say that I have a class Point(object) that represent 2d coordinates. Is it possible to create a "magic" method that will allow the following?

x, y = point

也许有一些使用迭代器的技巧?

Maybe some hacks with iterators?

推荐答案

只需提供一个__iter__方法.

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __iter__(self):
        yield self.x
        yield self.y

p = Point(1, 2)
x, y = p
assert (1, 2) == (x, y)

但是要小心.这意味着您的班级突然变得可以在以前可能引发类型错误的许多其他地方使用.

Be careful though. This means your class suddenly becomes safe to use in many other places where it might have previously thrown a type error.

例如

def add_1(x):
    return x + 1
l = list(map(add_1, p)) # works, because the point is iterable

Ergo,您可能要提供除提供迭代器的__iter__之外的方法.

Ergo, you may want to provide a method other than __iter__ that provides the iterator.

例如

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def coords(self):
        yield self.x
        yield self.y

p = Point(1, 2)
x, y = p.coords()
assert (1, 2) == (x, y)

这篇关于对象覆盖元组扩展的特殊方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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