可以在 __getitem__ 上使用多个参数吗? [英] Possible to use more than one argument on __getitem__?

查看:57
本文介绍了可以在 __getitem__ 上使用多个参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用

__getitem__(self, x, y):

在我的 Matrix 类上,但在我看来它不起作用(我仍然不太了解使用 python).我这样称呼它:

on my Matrix class, but it seems to me it doesn't work (I still don't know very well to use python). I'm calling it like this:

print matrix[0,0]

是否可以使用多个参数?谢谢.也许我只能使用一个参数但将其作为元组传递?

Is it possible at all to use more than one argument? Thanks. Maybe I can use only one argument but pass it as a tuple?

推荐答案

__getitem__ 只接受一个参数(除了 self),所以你会得到一个元组.

__getitem__ only accepts one argument (other than self), so you get passed a tuple.

你可以这样做:

class matrix:
    def __getitem__(self, pos):
        x,y = pos
        return "fetching %s, %s" % (x, y)

m = matrix()
print m[1,2]

输出

fetching 1, 2

请参阅文档,了解object.__getitem__ 了解更多信息.

See the documentation for object.__getitem__ for more information.

这篇关于可以在 __getitem__ 上使用多个参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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