简体   繁体   中英

Many levels of __getitem__ in Python

What to use to get more than one argument from another class? I need something like getitem () but with that i can get only 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

Python combines more than one argument of [...] into a tuple:

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]

You need to do it like this.

A.__getitem__() returns and another object with its own B.__getitem__() in which turn returns C.__getitem()__ . Then you can do

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

which is equivalent of saying

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM