python 可以在 __getitem__ 上使用多个参数吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1685389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Possible to use more than one argument on __getitem__?
提问by devoured elysium
I am trying to use
我正在尝试使用
__getitem__(self, x, y):
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:
在我的 Matrix 类上,但在我看来它不起作用(我仍然不太了解使用 python)。我这样称呼它:
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?
是否有可能使用多个参数?谢谢。也许我只能使用一个参数但将它作为元组传递?
回答by Chris AtLee
__getitem__
only accepts one argument (other than self
), so you get passed a tuple.
__getitem__
只接受一个参数(除了self
),所以你会得到一个元组。
You can do this:
你可以这样做:
class matrix:
def __getitem__(self, pos):
x,y = pos
return "fetching %s, %s" % (x, y)
m = matrix()
print m[1,2]
outputs
输出
fetching 1, 2
See the documentationfor object.__getitem__
for more information.
查看文档的object.__getitem__
更多信息。
回答by Alex Martelli
Indeed, when you execute bla[x,y]
, you're calling type(bla).__getitem__(bla, (x, y))
-- Python automatically forms the tuple for you and passes it on to __getitem__
as the second argument (the first one being its self
). There's no good way[1]to express that __getitem__
wants more arguments, but also no need to.
实际上,当您执行 时bla[x,y]
,您正在调用type(bla).__getitem__(bla, (x, y))
-- Python 自动为您形成元组并将其__getitem__
作为第二个参数传递给(第一个是它的self
)。没有什么好方法[1]来表达__getitem__
想要更多的论点,但也没有必要。
[1]In Python 2.*
you can actually give __getitem__
an auto-unpacking signature which will raise ValueError
or TypeError
when you're indexing with too many or too few indices...:
[1]在 Python 中,2.*
您实际上可以提供__getitem__
一个自动解包签名,该签名会引发ValueError
或TypeError
当您使用过多或过少的索引编制索引时...:
>>> class X(object):
... def __getitem__(self, (x, y)): return x, y
...
>>> x = X()
>>> x[23, 45]
(23, 45)
Whether that's "a good way" is moot... it's been deprecated in Python 3 so you can infer that Guido didn't consider it goodupon long reflection;-). Doing your own unpacking (of a single argument in the signature) is no big deal and lets you provide clearer errors (and uniform ones, rather than ones of different types for the very similar error of indexing such an instance with 1 vs, say, 3 indices;-).
这是否是“好方法”尚无定论……它在 Python 3 中已被弃用,因此您可以推断,经过长时间的反思,Guido 并不认为它是好的;-)。自己解包(签名中的单个参数)没什么大不了的,并且可以让您提供更清晰的错误(和统一的错误,而不是不同类型的错误,因为使用 1 vs 索引此类实例的非常相似的错误,例如, 3 个指数;-)。
回答by Mike Graham
No, __getitem__
just takes one argument (in addition to self
). In the case of matrix[0, 0]
, the argument is the tuple (0, 0)
.
不,__getitem__
只需要一个参数(除了self
)。在 的情况下matrix[0, 0]
,参数是元组(0, 0)
。