Python中的许多级别的getitem

2024-04-20 08:41:42 发布

您现在位置:Python中文网/ 问答频道 /正文

使用什么从另一个类获取多个参数?我需要像getitem()这样的东西,但是这样我只能得到1个。你知道吗

class Example(object):

    def __init__(self, ex1, ex2, ex3):
        self.ex1 = ex1
        self.ex2 = ex2
        self.ex3 = ex3
   #just example, this will not work
   def __getitem__(self, ex1, ex2, ex3):
   return self.ex1, self.ex2, self.ex3

Tags: self参数objectinitexampledefthiswill
2条回答

你得这样做。你知道吗

A.__getitem__()返回另一个对象,它有自己的B.__getitem__(),然后返回C.__getitem()__。那你就可以了

b = a["1"]
c = b["2"]

也就是说

 c = a["1"]["2"]

Python将[...]的多个参数组合成一个元组:

class Example(object):

    def __init__(self, ex1, ex2, ex3):
        self.ex1 = ex1
        self.ex2 = ex2
        self.ex3 = ex3

    def __getitem__(self, index):
       ex1, ex2, ex3 = index
       return self.ex1, self.ex2, self.ex3

ex = Example(1,2,3)
print ex[1,2,3]

相关问题 更多 >